0 haskell functional-programming typeclass
我正在Haskell中编写一个小函数来检查列表是否是回文,并将其与反向进行比较.
checkPalindrome :: [Eq a] -> Bool
checkPalindrome l = (l == reverse l)
where
reverse :: [a] -> [a]
reverse xs
| null xs = []
| otherwise = (last xs) : reverse newxs
where
before = (length xs) - 1
newxs = take before xs
Run Code Online (Sandbox Code Playgroud)
我知道我应该在函数定义中使用[Eq a],因为我稍后使用了相等运算符,但是在编译时遇到了这个错误:
Expected kind ‘*’, but ‘Eq a’ has kind ‘GHC.Prim.Constraint’
In the type signature for ‘checkPalindrome’:
checkPalindrome :: [Eq a] -> Bool
Run Code Online (Sandbox Code Playgroud)
如果我的缩进做错了,请随意纠正我,我对这门语言很新.
除非Haskell采用新语法,否则您的类型签名应为:
checkPalindrome :: Eq a => [a] -> Bool
Run Code Online (Sandbox Code Playgroud)
在fat-arrow的左侧声明约束,然后在右侧使用它.
| 归档时间: |
|
| 查看次数: |
357 次 |
| 最近记录: |