初始化错误地当作参数
问题描述:
isPalindrome :: Eq a => [a] -> Bool
isPalindrome [] = True
isPalindrome [a] = True
isPalindrome (x:xs) = (x == last xs) && (isPalindrome init xs)
返回我初始化错误地当作参数
Couldn't match expected type `[a0]' with actual type `[a1] -> [a1]'
In the first argument of `isPalindrome', namely `init'
In the second argument of `(&&)', namely `(isPalindrome init xs)'
In the expression: (x == last xs) && (isPalindrome init xs)
我不明白为什么哈斯克尔认为isPalindrome的参数初始化而它的init XS
答
在Haskell,无形功能应用运营商联营的左侧,所以isPalindrome init xs
被解释为(isPalindrome init) xs
。这是因为它可以让我们使用currying使用多个参数来处理函数实现这种方式。
要通过init xs
作为一个参数,你只需要使用括号:
isPalindrome (init xs)
+0
一美元也将做到这一点:'isPalindrome $初始化xs' – MathematicalOrchid
+0
捐赠一元钱的表达。 – user3974391
功能应用是左结合的,这意味着它从评估左到右。 'isPalindrome INIT xs'是一样的'(isPalindrome INIT)xs' - 你想要它周围的其他方式,这意味着你需要额外的括号:'isPalindrome(INIT XS)'。 – Xeo
作品,非常感谢XEO – user2741700