我对使用 Haskell 很陌生,我不确定“head”是如何工作的。根据我的理解,它返回列表中的第一个元素。我一直在尝试使用它,但我不断收到错误消息。我通过创建一个单独的函数来找到头部来添加一个解决方法,但这似乎是不必要的。
我不明白为什么在这里调用 findHead:
single x = length (snd(x)) == 1
toList board
| board == [] = []
| otherwise = filter single board
findHead board = head (toList board)
不等同于在此处调用 toList:
single x = length (snd(x)) == 1
toList board
| board == [] = []
| otherwise = head (filter single board)
在我看来,两者应该是一样的,但只有第一个运行。为什么它们不被解释为相同?你能向我解释一下吗?在上面的代码中,'board' 是一个元组列表,每个元组的形式都是 (x, [a,b,...])。
我在一些更简单的事情中使用了“头”,例如:
union xs ys
| xs == [] = ys
| ys == [] = xs
| otherwise = union (tail xs) (add (head xs) ys)
这似乎像我期望的那样工作。
最佳答案
head
是部分的。特别是,head []
不会正常返回(抛出异常)。这在 Haskell 中很难处理,这就是为什么人们经常建议您避免使用部分函数的原因。
那么我们该怎么做呢?我们必须在类型中反射(reflect)失败。
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (a:as) = Just a
tail
也可以做类似的功能safeTail :: [a] -> Maybe [a]
safeTail [] = Nothing
safeTail (a:as) = Just as
关于haskell - 在 Haskell 中,如何在不创建单独函数的情况下使用 'head'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29266072/