匹配列表与其他列表列表

时间:2016-11-12 16:57:32

标签: haskell

嘿伙计我有关于匹配列表的问题

鉴于列表清单:

Input List 1  = [[True],[False],[True],[[False]]
Input List 2 = [[Bob],[Rick],[Lee],[Bill]]
Input List 3 = [[1],[2],[3],[4]]

然后将列表1的布尔值与其他列表匹配,以便发生这种情况:

Input List 1 + Input List 2 = [[Bob],[Dead],[Lee],[Dead]]
Input List 1 + Input List 2 = [[1],[0],[3],[0]]

3 个答案:

答案 0 :(得分:2)

据我所知,这里使用嵌套列表是不必要的。没有它们,您需要的只是zipWith和适当的组合功能:

-- The first argument is the "dead" value. Note that this works with any type.
makeDead :: a -> Bool -> a -> a
makeDead dead b val
    | b = val
    | otherwise = dead
GHCi> :t zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
GHCi> zipWith (makeDead "Dead") [True,False,True,False] ["Bob","Rick","Lee","Bill"] 
["Bob","Dead","Lee","Dead"]

主题的两个变体。首先,如果值是否应该更改取决于值是什么,那么您只需使用map / fmap

 -- Affects all names with 'i' as the second letter:
lethalLetter :: String -> String
lethalLetter name -> case name of
    (_:'i':_) -> "Dead"
    _ -> name
GHCi> fmap lethalLetter ["Bob", "Rick", "Lee", "Bill"]
["Bob","Dead","Lee","Dead"]

其次,您可能更喜欢使用Maybe来表示死亡而不是使用任意值(如果某人实际被称为"死"那么?)

makeDead' :: Bool -> a -> Maybe a
makeDead' b val
    | b = Just val
    | otherwise = Nothing
GHCi> zipWith makeDead' [True,False,True,False] ["Bob","Rick","Lee","Bill"] 
[Just "Bob",Nothing,Just "Lee",Nothing]

然后,您可以使用maybefromMaybecatMaybes等函数(后两者在Data.Maybe中)来摆脱Nothing但是你觉得这样做:

GHCi> import Data.Maybe
GHCi> foo = zipWith makeDead' [True,False,True,False] ["Bob","Rick","Lee","Bill"]
GHCi> catMaybes foo
["Bob","Lee"]

答案 1 :(得分:0)

假设您按照duplode的建议将它们更改为列表,如何在列表解析中将两个列表压缩在一起,如下所示:

[if flag then val else defaultVal  | (flag, val) <- zip(list1, list2)]

必须指定defaultVal,但对于列表2和3,似乎是Dead0

(我现在无法访问Haskell,因此语法可能不是100%,但这就是主意。)

答案 2 :(得分:0)

您可以使用zipWith . zipWith :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]来匹配列表列表。例如:

import Data.Bool (bool)
kill deadVal = zipWith . zipWith $ bool (const deadVal) id

example = kill 0 [[True, False],[False,True]] [[1,2,3],[2]]
-- example = [[1,0],[0]]