我正在尝试使用查询显示表中的几列。但是我收到一条错误消息:
* Couldn't match type `Char' with `[Char]'
Expected type: [[[Field]]]
Actual type: [[[Char]]]
* In the second argument of `mapMaybe', namely
`(map transpose (table))'
In the expression:
mapMaybe (elemIndex columns) (map transpose (table))
In an equation for `project':
project columns table@(header : _)
= mapMaybe (elemIndex columns) (map transpose (table))
我的Haskell代码如下:
project columns table@(header : _)
= mapMaybe (elemIndex columns) (map transpose (table))
table
的类型为Table
,即[Row]
或[[Field]]
。 Field
是String
的同义词。
答案 0 :(得分:2)
让我们先浏览一下我们正在使用的功能的签名:
elemIndex
具有以下签名:
elemIndex :: Eq a => a -> [a] -> Maybe Int
mapMaybe
具有以下签名:
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
然后,我们可以根据其参数elemIndex
(从我期望的名称来看,其类型为columns
)着手[Field]
的类型:
elemIndex :: [Field] -> [[Field]] -> Maybe Int
因此:
elemIndex columns :: [[Field]] -> Maybe Int
然后让我们根据第一个参数mapMaybe
对elemIndex columns
进行同样的专业化处理:
mapMaybe :: ([[Field]] -> Maybe Int) -> [[[Field]]] -> Int
因此:
mapMaybe (elemIndex columns) :: [[[Field]]] -> Int
但是我希望根据您所说的table
是Table
,您所说的是[Row]
,这是[[Field]]
,并且不能扮演必需的[[[Field]]]
的角色。
那为什么会发生呢?我认为您在滥用elemIndex
。 elemIndex
是一个函数,给定类型为a
的值和类型为[a]
的列表,该函数在列表中找到该值首次出现的索引并返回{{1} },或者Just
(如果根本不存在):
Nothing
但是,您似乎想给它一个类型elemIndex 5 [1, 2, 3, 4, 5]
> 4
的值和一个列表a
的列表的列表,并获取第一个子列表的索引以该值开头:
[[a]]
此功能在标准库(或我所知道的任何库)中不存在。我建议使用函数elemIndex' 5 [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]
> 4
:
elemIndexBy