3

这是我的代码,但是,我不知道这是怎么回事,这是我的代码:

ll :: [a] ->  a
ll lis = case lis of
  (_:xs) -> ll xs
  [] -> error"xx"

并且终端没有错误消息:但是当我运行“ll [1, 2, 3]”时,我想得到“3”,但是,我得到了“ * Exception:xx”的结果。

谁喜欢告诉我它有什么问题?谢谢XD

4

3 回答 3

12

You're never returning the last element of the list. The first case clause drops the first element of a non-empty list then recursively calls ll. Eventually, you'll hit the empty list case and hence the error gets raised.

于 2013-04-14T16:39:30.237 回答
6

我发现从递归的基本情况开始很有帮助:

ll [x] = x

然后递归:

ll (_:xs) = ll xs

当然,提供有用的错误信息是一种很好的风格。当没有大小写匹配时,最后这样做通常很方便:

ll _ = error "empty list"

作为奖励,WTF!?!版本:

import Data.List

ll = foldl' (flip const) (error "empty list")

你可以调用flip const“阿尔茨海默氏症函数”,它只是忘记了它的第一个参数并返回第二个参数,并且当foldl'从左到右挖掘列表时,它会给你最后一个元素。

于 2013-04-14T18:16:20.627 回答
1

使用预定义函数的最简单实现:

ll = head . reverse
于 2013-04-14T21:21:12.570 回答