gpt4 book ai didi

haskell - 初学者haskell程序员

转载 作者:行者123 更新时间:2023-12-03 14:40:08 24 4
gpt4 key购买 nike

isPalindrome::(Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome [x] = True
isPalindrome (x1:xs:x2:[])
| x1 == x2 = isPalindrome xs
|otherwise = False


[1 of 1] Compiling Main ( myHas.hs, interpreted )

myHas.hs:37:27:
Couldn't match expected type `[a]' against inferred type `a1'
`a1' is a rigid type variable bound by
the type signature for `isPalindrome' at myHas.hs:33:18
In the first argument of `isPalindrome', namely `xs'
In the expression: isPalindrome xs
In the definition of `isPalindrome':
isPalindrome (x1 : xs : x2 : [])
| x1 == x2 = isPalindrome xs
| otherwise = False

我是初学者haskell程序员,不知道为什么会出现此错误,请帮忙?

最佳答案

你对待xs像一个列表,但是 (x1:xs:x2:[])假设它是您输入列表的一个元素。

请注意 (x1:xs:x2:[])将仅匹配具有 3 个元素的列表,并且 x1 , xsx2将是 a 类型的元素.

所以xsa 类型, 但是当你把它传递给 isPalindrome ,我们只能假设它一定是一个列表,所以类型系统调用类型 [a1] .

编码你想要的最简单的方法是:

isPalindrome::(Eq a) => [a] -> Bool
isPalindrome l = l == (reverse l)

关于haskell - 初学者haskell程序员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7315879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com