問題
PureScript で Maybe a を a にしたい (値を取り出したい) 。どうすれば良いのか。
解決策
あくまで一例。
- case などのパターンマッチで取り出す。
-
maybe
(https://pursuit.purescript.org/packages/purescript-maybe/2.0.1/docs/Data.Maybe#v:maybe) を使う。 -
fromMaybe
(https://pursuit.purescript.org/packages/purescript-maybe/2.0.1/docs/Data.Maybe#v:fromMaybe) を使う。 -
fromJust
(https://pursuit.purescript.org/packages/purescript-maybe/2.0.1/docs/Data.Maybe#v:fromJust) +unsafePartial
を使う。
基本的には値がない (Nothing) ときの代わりの値については考えないといけない。次の例では 456
を使っている。
fromJust
は Nothing のパターンを考慮していない部分関数。 unsafePartial
を使って、危険を承知で Just
前提で抜き出す。
case
> import Data.Maybe (Maybe(..))
> let m1 = Just 123
> let m2 = Nothing
>
> :paste
… case m1 of
… Nothing -> 456
… Just x -> x
…
123
> :paste
… case m2 of
… Nothing -> 456
… Just x -> x
…
456
maybe
> import Data.Maybe (Maybe(..), maybe)
> let m1 = Just 123
> let m2 = Nothing
>
> maybe 456 (\x -> x) m1
123
> maybe 456 (\x -> x) m2
456
fromMaybe
> import Data.Maybe (Maybe(..), fromMaybe)
> let m1 = Just 123
> let m2 = Nothing
>
> fromMaybe 456 m1
123
> fromMaybe 456 m2
456
fromJust
(+ unsafePartial
)
> import Data.Maybe (Maybe(..), isJust, fromJust)
> import Partial.Unsafe (unsafePartial)
> let m1 = Just 123
> let m2 = Nothing
>
> if isJust m1 then unsafePartial fromJust m1 else 456
123
> if isJust m2 then unsafePartial fromJust m2 else 456
456
> unsafePartial fromJust m1
123
> unsafePartial fromJust m2 :: Maybe Int
...
Error: Failed pattern match
...
実装
ちなみにそれぞれの実装は次の通り。
maybe
https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L213-L213
maybe :: forall a b. b -> (a -> b) -> Maybe a -> b
maybe b _ Nothing = b
maybe _ f (Just a) = f a
fromMaybe
https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L238-L238
fromMaybe :: forall a. a -> Maybe a -> a
fromMaybe a = maybe a id
fromJust
https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L264-L265
fromJust :: forall a. Partial => Maybe a -> a
fromJust (Just x) = x
参考
- https://pursuit.purescript.org/packages/purescript-maybe/2.0.1/docs/Data.Maybe#v:maybe
- https://pursuit.purescript.org/packages/purescript-maybe/2.0.1/docs/Data.Maybe#v:fromMaybe
- https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L213-L213
- https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L238-L238
- https://github.com/purescript/purescript-maybe/blob/v2.0.1/src/Data/Maybe.purs#L264-L265