[英]List of Tuples as a function Parameter in Haskell
How do define a function with a parameter that is a list of tuples? 如何使用包含元组列表的参数定义函数? So an example of the input would be
所以输入的一个例子是
[("hey", False), ("you", True)]
My function takes the list of tuples as: [(String, Bool)] So here is what it looks like: 我的函数将元组列表作为:[(String,Bool)]因此,它看起来像这样:
aFunc :: [(String, Bool)] -> Bool
aFunc ???? =
So what do I fill in for the ???? 那我该为什么填写???? to be able to access my tuple?
可以访问我的元组? Any help would be great.
任何帮助都会很棒。 Thanks.
谢谢。
Edit: 编辑:
aFunc :: [(String, Bool)] -> Bool
aFunc aTuple = mapM_ lookup aTuple?
So how do I access my tuple in a function? 那么如何在函数中访问我的元组呢? That doesn't work.
那不行
It looks like you're trying to implement your own version of lookup
. 看来您正在尝试实现自己的
lookup
版本。 You can write a simple version using list comprehension: 您可以使用列表推导编写一个简单的版本:
lookup' :: String -> [(String,Bool)] -> Bool
lookup' k lkp = head $ [v | (k',v) <- lkp, k'==k]
Or using filter
: 或使用
filter
:
lookup'' :: String -> [(String,Bool)] -> Bool
lookup'' k lkp = snd $ head $ filter ((==k) . fst) lkp
Notice that these versions are unsafe - that is, they'll fail with an ugly and uninformative error if the list doesn't contain your item: 请注意,这些版本不安全-也就是说,如果列表中不包含您的商品,它们将以丑陋且无信息的错误失败:
ghci> lookup' "foo" [("bar",True)]
*** Exception: Prelude.head: empty list
You can solve this issue by writing your own custom error message: 您可以通过编写自己的自定义错误消息来解决此问题:
lookupErr :: String -> [(String,Bool)] -> Bool
lookupErr k lkp = case [v | (k',v) <- lkp, k'==k] of
(v:_) -> v
[] -> error "Key not found!"
A better approach is to return a Maybe Bool
instead: 更好的方法是返回
Maybe Bool
代替:
lookupMaybe :: String -> [(String,Bool)] -> Maybe Bool
lookupMaybe k lkp = case [v | (k',v) <- lkp, k'==k] of
(v:_) -> Just v
[] -> Nothing
The library version takes this approach, and has a more generic signature: 库版本采用这种方法,并具有更通用的签名:
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.