fugafuga.write

日々のログ

すごいH本 part51

YesNo 型クラスをつくる

JavaScript 的なゆるふわ真理値の型クラスをつくる

class YesNo a where
    yesno :: a -> Bool

真理値の概念を何らかの形で含むとみなせる型の値を取り、それが true かどうかを返す。

インスタンスを定義する

instance YesNo Int where
    yesno 0 = False
    yesno _ = True

instance YesNo [a] where
    yesno [] = False
    yesno _ = True

instance YesNo Bool where
    yesno = id

instance YesNo (Maybe a) where
    yesno (Just _) = True
    yesno Nothing = False

instance YesNo (Tree a) where
    yesno EmptyTree = False
    yesno _ = True

instance YesNo TrafficLight where
    yesno Red = False
    yesno _ = True

id は引数を一つ取って同じものを返す標準関数。

実行

*Main> yesno $ length []
False
*Main> yesno "haha"
True
*Main> yesno ""
False
*Main> yesno $ Just 0
True
*Main> yesno True
True
*Main> yesno EmptyTree
False
*Main> yesno []
False
*Main> yesno [0,0,0]
True
*Main> :t yesno
yesno :: YesNo a => a -> Bool

if っぽい関数を実装する

yesnoIf :: (YesNo y) => y -> a -> a -> a
yesnoIf yesnoVal yesResult noResult =
        if yesno yesnoVal
            then yesResult
            else noResult

実行

*Main> yesnoIf [] "YES!!" "NO!!"
"NO!!"
*Main> yesnoIf [2,3,4] "YES!!" "NO!!"
"YES!!"
*Main> yesnoIf True "YES!!" "NO!!"
"YES!!"
*Main> yesnoIf (Just 400) "YES!!" "NO!!"
"YES!!"
*Main> yesnoIf Nothing "YES!!" "NO!!"
"NO!!"

所感

型クラスの関数にそのインスタンスを適用すると、型によって実装が違うので振る舞いが変わる。多態性を表現できるようになった。

すごいHaskellたのしく学ぼう!

すごいHaskellたのしく学ぼう!

  • 作者: MiranLipovaca
  • 出版社/メーカー: オーム社
  • 発売日: 2017/07/14
  • メディア: Kindle版
  • 購入: 4人 クリック: 9回
  • この商品を含むブログを見る