【发布时间】:2018-06-02 13:29:40
【问题描述】:
嘿,我是 Haskell 的新手,想弄清楚如何返回一个长度为 n 的单词的列表
getWords :: Int -> [Word] -> [Word]
getWords n w = filter (\x -> length x == n) w
我发现我可以在 Prelude 中使用它 过滤器 (\x -> 长度 x == 5) ["Hello", "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
我在这里做错了什么?
【问题讨论】:
-
您希望
"Hello"具有什么类型?根据 Haskell 文档,Word是哪种数据类型? -
在这种情况下是
Word只是String还是[Char]? -
Word是数字类型,除非您以某种方式重新定义了它。你想要一个字符串列表,即getWords :: Int -> [String] -> [String] -
@RoadRunner 没关系;
type String = [Char].