Haskell:将索引列表映射到字符串

时间:2017-03-02 00:49:48

标签: haskell dictionary indexing

你好:我有一个句子分解为单词:

["this", "is", "a", "simple", "sentence"]

我有一个indices = [0, 2, 4]

列表

我试图将索引列表映射到句子上以返回适当索引处的单词,如下所示: 如果我们将indices [0, 2, 4]应用于我们获得的句子:

["this", "a", "sentence"]

这是我的代码:

sentence !! [x | x <- indices]

这是错误消息:

  <interactive>:215:7: error:
• Couldn't match expected type ‘Int’ with actual type ‘[Integer]’
• In the second argument of ‘(!!)’, namely ‘[x | x <- indices]’
  In the expression: tex !! [x | x <- indices]
  In an equation for ‘it’: it = sentence !! [x | x <- indices

我对使用(!!)和/或列表推导的答案特别感兴趣。

谢谢

2 个答案:

答案 0 :(得分:5)

你几乎就在那里你的例子中只有一个括号错误 改变:

sentence !! [x | x <- indices] -- (1)

为:

[sentence !! x | x <- indices] -- (2)

但是为什么 - 在“list comprehension(1)”中你尝试将索引操作符!!应用于索引列表,编译器告诉你它需要Int(即索引)但你提供一个清单。

后者(2)有效,因为对于每个索引 - 我从列表sentence中获取该索引的元素。

旁注:作为初学者,这没关系 - 但是如果你的列表很长并且你的索引在最后 - 这需要一些时间,列表不是最适合索引的数据结构 - Array s,IntMapSeq更适合

EDIT2:

如果你想让你的大脑继续前进 - 想想可能

zipWith (!!) (repeat sentence) indices

DO

答案 1 :(得分:4)

这可能看起来有点奇怪,但(sentence !!)实际上是(部分应用的)function,类型为:: Int -> [Char]。您可以map将其添加到索引列表中以获得所需的结果:

> map (["this", "is", "a", "simple", "sentence"] !!) [0, 2, 4]
> ["this","a","sentence"]
相关问题