Haskell-搜索对列表 [英] Haskell - Searching through a list of pairs
问题描述
我正在尝试制作某种东西,以便它需要一本书和一个字符串,然后返回与该书中的字符串相关联的值...所以到目前为止,我是这样的:
I'm trying to make something so that it takes a Book and a string and then returns the value that's associated with the string in the book... so what I have so far is:
data Answer = T | F
deriving (Eq, Show, Ord)
type Book = [(String, Answer)]
testBook :: Book
testBook = [("aT", T), ("bF", F)]
我想这样做,所以我说:
and I want to do it so that let's say i put:
test testBook "aT"
^答案将传给T.
我正在做类似的事情:
test::Book->String->Answer
test a b = [x | (y, x) <- a, y == b]
但是我知道那完全不合时宜.我如何比较String和Book中的内容?看起来很简单,但是Haskell的语法确实很难习惯
but i know that's completely off.. how can I compare the String to what's in the Book? it seems simple but the syntax for Haskell is really hard to get used to
推荐答案
您的代码在正确的轨道上.现在,您将获得无论值为b
的答案的列表.您需要添加一个条件,以检查元组的第一项是否等于b
;为此,您必须给它起一个名字而不是使用_
.
Your code is on the right track. Right now, you get a list of answers regardless of the value of b
. You need to add a condition that checks whether the first item of the tuple is equal to b
; to do this, you will have to give it a name rather than using _
.
您可以使用逗号和表达式将条件添加到列表理解:
You can add a condition to a list comprehension by using a comma and an expression:
[x | x <- a, x > 10]
例如,
将从a
中获取大于10的所有值.
will get you all the values from a
greater than 10, for example.
我会让你想出如何自己提出建议的方法.
I will let you figure out how to put my advice together yourself.
这篇关于Haskell-搜索对列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!