Haskell中的函数定义

时间:2014-10-31 10:34:37

标签: haskell

我有2个样品问题,我无法解决它们

第一个

abss :: Int->Int
abss x 
        | x<0           =x
        | otherwise     =-x

第二个

headd ::[a]->a
headd [x,_] = x

1 个答案:

答案 0 :(得分:6)

让我试试:

abss :: Int->Int
abss x 
        | x<0           =x
        | otherwise     = -x

你写它的方式Haskell会假设运算符=-在那里 - 你需要空间;)

headd ::[a]->a
headd (x:_) = x

在这里,您希望head版本查看非空列表的第一个元素(其格式为x:rest[x,_]只会匹配[1,2],&#34; ab&#34;,...但不是[1,2,3],&#34; abc&#34;,..

BTW:我假设您希望此函数是部分的(就像head一样) - 您可以通过以下方式摆脱编译器警告:

headd ::[a]->a
headd [] = error "no head on empty list"
headd (x:_) = x

如果你想要

相关问题