點燈坊

失くすものさえない今が強くなるチャンスよ

使用 toMaybe 將 Value 轉成 Maybe

Sam Xiao's Avatar 2021-07-30

Sanctuary 雖然有提供 JustNothing 回傳 Maybe,卻沒有辦法將任何 Value 直接轉成 Maybe,Wink-fp 特別提供 toMaybe

Version

Wink-fp 1.28.5

toMaybe

import { isNil } from 'ramda'
import { Just, ifElse } from 'sanctuary'
import { N } from 'wink-fp'

let toMaybe = ifElse (isNil) (N) (Just)

toMaybe (2) // ?
toMaybe (null) // ?
toMaybe (undefined) // ?

第 5 行

let toMaybe = ifElse (isNil) (N) (Just)

特別使用 ifElse 搭配 isNil 判斷,若為 nullundefined 則回傳 Nothing,否則回傳 Just。

tomaybe000

Wink-fp

import { toMaybe } from 'wink-fp'

toMaybe (undefined) // ?
toMaybe (null) // ?
toMaybe (2) // ?

Wink-fp 已經提供 toMaybe 可直接使用。

toMaybe :: a -> Just | Nothing
將任意 value 轉型成 Just 或 Nothing

a:傳入任意型別值

Just | Nothing:回傳 Just 或 Nothing

tomaybe001

find

import { find as _find } from 'ramda'
import { pipe, equals, maybe, I } from 'sanctuary'
import { toMaybe } from 'wink-fp'

let find = f => pipe ([
  _find (f),
  toMaybe
])

let data = [1, 2, 3]

pipe ([
  find (equals (5)),
  maybe ('N/A') (I)
]) (data) // ?

第 5 行

let find = f => pipe ([
  _find (f),
  toMaybe
])

使用 pipe 組合回傳 Maybe 的 find

  • _find (f):Ramda 的 find 是典型會回傳 undefined 的 function,特別 alias 為 _find
  • toMaybe:將 _find 回傳值轉成 Maybe

find 相當於 Sanctuary 的 find

12 行

pipe ([
  find (equals (5)),
  maybe ('N/A') (I)
]) (data) // ?

使用 pipe 組合 IIFE:

  • find (equals (5)):使用自行組合的 find
  • maybe ('N/A') (I):因為回傳 Maybe,需使用 maybe 解開

tomaybe002

Conclusion

  • toMaybe 曾經內建於 Sanctuary,後來因故從 Sanctuary 中移除,特別在 Wink-fp 提供 toMaybe

Reference

Sanctuary, Maybe