在haskell类型匹配错误

时间:2014-06-12 14:08:53

标签: haskell

我正在使用拥抱编译一个简单的Haskell函数。但是我的函数会出现类型错误 这是功能:

expression :: Int -> Int -> Int
expression n d  = countN d 0 0 (div n 2)

countN :: Int->Int->Int->Int->Int
countN goal now max left 
=
if(left == 0 && max == goal) then 1
else if(left == 0) then 0
else if(max > goal || now>left) then 0
else if(now == 0) then countN(goal now+1 (if(now+1>max) then now+1 else max) left)
else countN(goal now+1 (if(now+1>max) then now+1 else max) left) + countN(goal now-1 max left-1)

这是错误:

 Type error in application
 *** Expression     : goal now
 *** Term           : goal
 *** Type           : Int
 *** Does not match : a -> b

1 个答案:

答案 0 :(得分:2)

问题在于你的代码的这一部分。

countN(goal now-1 max left-1)

haskell将此解释为......

countN ((goal now) - (1 (max left)) - 1)

...这显然不是你的意思,但是haskell看到你试图用goal的参数调用nowgoal的类型为Int,但您通过尝试对其应用参数将其视为a -> b,因此类型错误。

记住whitspace是函数应用程序,运算符具有更高的函数应用程序优先级,也许你的意思是:

countN goal (now-1) max (left-1)

这将使你的最终表达成为:

(countN goal (now+1) next left) + (countN goal (now-1) max (left-1))
    where next = if now+1 > max then now+1 else max