soy-curd's blog

へぼプログラマーです [https://twitter.com/soycurd1]

ElmのMaybe

Elmにはモナドはないようだが、Maybeはモジュールとして用意されている。以下、簡単に使ってみたメモ。

Maybeを作る

特に明示的にimportしなくてもMaybeは使える。以下はif式で場合分けし、Just aかNothingを返す関数の例。

-- 0未満100以上はNothingにするMaybe
numUnder100 : Int -> Maybe Int
numUnder100 xs =
  if
    |(xs < 0) -> Nothing
    |(xs < 100) -> Just xs
    |otherwise -> Nothing

-- < 50 を"ほげ!"
-- < 100 を"ほげ..."にするMaybe
num2Hoge : Int -> Maybe String
num2Hoge xs =
  if
    |(xs < 50) -> Just "ほげ!"
    |(xs < 100) -> Just "ほげ..."
    |otherwise -> Nothing

caseでMaybeをはずす

case式でJustかNothingをマッチングさせて、Maybeから値を取り出している。

-- Maybeをはずす
checkMaybe : Maybe String -> String
checkMaybe intmaybe =
  case intmaybe of
    Just xs -> xs
    Nothing -> ""

Maybeのチェーン

Maybe.andThenを用いてMaybeをチェーンしている。'andThen'だけだと他のモジュールと競合するため、'Maybe.andThen'とする必要がある。なお、バッククォートで囲んでいるのは、中置記法でandThenを使うため。

-- andThenはMaybeをチェーンできる
andThenExample : Int -> Maybe String
andThenExample num =
  numUnder100 num `Maybe.andThen` num2Hoge

おわりに

以上を利用したちょっとしたサンプルが以下。

import Graphics.Element exposing (..)
import Mouse
import Signal exposing(..)

-- 0未満100以上はNothingにするMaybe
numUnder100 : Int -> Maybe Int
numUnder100 xs =
  if
    |(xs < 0) -> Nothing
    |(xs < 100) -> Just xs
    |otherwise -> Nothing

-- < 50 を"ほげ!"
-- < 100 を"ほげ..."にするMaybe
num2Hoge : Int -> Maybe String
num2Hoge xs =
  if
    |(xs < 50) -> Just "ほげ!"
    |(xs < 100) -> Just "ほげ..."
    |otherwise -> Nothing

-- Maybeをはずす
checkMaybe : Maybe String -> String
checkMaybe intmaybe =
  case intmaybe of
    Just xs -> xs
    Nothing -> ""

-- andThenはMaybeをチェーンできる
andThenExample : Int -> Maybe String
andThenExample num =
  numUnder100 num `Maybe.andThen` num2Hoge

-- マウスの位置によってメッセージが変る
main =
  show <~
    (checkMaybe <~
      (andThenExample <~
          Mouse.x))