嘿,我是Haskell的新手并试图找出如何返回长度为n的单词的列表
getWords :: Int -> [Word] -> [Word]
getWords n w = filter (\x -> length x == n) w
我发现我可以在Prelude中使用它 过滤器(\ x - >长度x == 5)[“你好”,“23”]
它将返回[“Hello”],但是当我尝试在函数getWords中执行它时它会给我一个错误
* Couldn't match type `t0 a0' with `Word'
Expected type: [Word]
Actual type: [t0 a0]
* In the expression: filter (\ x -> length x == n) w
In an equation for `getWords':
getWords n w = filter (\ x -> length x == n) w
|
163 | getWords n w = filter (\x -> length x == n) w
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Date.hs:163:45: error:
* Couldn't match type `Word' with `t0 a0'
Expected type: [t0 a0]
Actual type: [Word]
* In the second argument of `filter', namely `w'
In the expression: filter (\ x -> length x == n) w
In an equation for `getWords':
getWords n w = filter (\ x -> length x == n) w
|
163 | getWords n w = filter (\x -> length x == n) w
我在这里做错了什么?
答案 0 :(得分:2)
你做错了是假设Word
来自Data.Word
。这是一个机器字,如无符号整数值。它不是一个人类的单词,就像字符串中的字母一样。正如@chi的评论中所述,您应该使用[String]
:
getWords :: Int -> [String] -> [String]
getWords n w = filter (\x -> length x == n) w