我一直在研究'真实世界Haskell',我一直在努力研究如何使用Maybe.我从第3章开始编写了这种数据类型和相应的函数.本书建议尝试将其转换为使用Maybe并摆脱Nil类型.我一直在玩这个,但我无法弄清楚如何做到这一点.我尝试过在不同的地方添加,但我真的只是猜测而不是知道如何去做.
data List a = List a (List a)
| Nil
deriving (Show)
toList :: List a -> [a]
toList (List a Nil) = a:[]
toList (List a as) = a:(toList as)
Run Code Online (Sandbox Code Playgroud)
看这个:
data List a data Maybe a
= List a (List a) = Just a
| Nil | Nothing
Run Code Online (Sandbox Code Playgroud)
当你用这种方式编写时,并行看起来非常清楚 - 我们只需要在Just侧面添加一些额外的数据!要放置"额外"数据,我们可以使用元组.唯一的另一个问题是我们必须命名一个构造函数.
data List' a = List' (Maybe (a, List' a {- here's the extra bit -}))
Run Code Online (Sandbox Code Playgroud)