oma*_*mar 1 indexing dictionary haskell
您好:我有一个句子分解为单独的单词:
["this", "is", "a", "simple", "sentence"]
Run Code Online (Sandbox Code Playgroud)
我有一份清单 indices = [0, 2, 4]
我试图将索引列表映射到句子上以返回适当索引处的单词,如下所示:如果我们应用于indices [0, 2, 4]句子,我们得到:
["this", "a", "sentence"]
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
sentence !! [x | x <- indices]
Run Code Online (Sandbox Code Playgroud)
这是错误消息:
<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
Run Code Online (Sandbox Code Playgroud)
我对使用(!!)和/或列出理解的答案特别感兴趣.
谢谢
你几乎就在那里你的例子改变只有一个括号错误:
sentence !! [x | x <- indices] -- (1)
Run Code Online (Sandbox Code Playgroud)
至:
[sentence !! x | x <- indices] -- (2)
Run Code Online (Sandbox Code Playgroud)
但是为什么 - 在"list comprehension(1)"中你试图将索引操作符应用于索引!!列表,并且编译器告诉你它期望Int(即索引)但是你提供了一个列表.
后者(2)有效,因为对于每个索引 - 我从列表中获取该索引的元素sentence.
旁注:作为初学者,这没关系 - 但是如果你的列表很长并且你的索引在最后 - 这需要一些时间,列表不是最适合索引的数据结构 - Arrays,IntMaps,并且Seq更适合
如果你想让你的大脑继续前进 - 想想会发生什么
zipWith (!!) (repeat sentence) indices
Run Code Online (Sandbox Code Playgroud)
做