LoginSignup
5
3

More than 5 years have passed since last update.

PureScript で Maybe a を a にする

Last updated at Posted at 2017-01-29

問題

PureScript で Maybe a を a にしたい (値を取り出したい) 。どうすれば良いのか。

解決策

あくまで一例。

基本的には値がない (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

参考

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3