我想检查列表中的任何元素是否与其他列表Haskell的任何元素匹配

时间:2014-10-16 23:50:49

标签: haskell

模块Dominoes

type Domino = [(Int, Int)]
type Hand = Domino
type Board = Hand
type End = Board


dominoes :: Domino
dominoes = [(x, y)| x <- [0..6], y <- [x..6]]

amount_to_take = 7

hand :: Domino -> Domino
hand x  = take amount_to_take x

我想检查Domino的任何元素是否与End的任何元素匹配。如果是,则返回true,如果不是

,则返回false
goesP :: Domino -> End -> Bool 
goesP (h:t) (h1:t1) 
  |   h == h1 = True
  |   t == t1 = True
  |  otherwise False

1 个答案:

答案 0 :(得分:2)

goesP :: Domino -> End -> Bool
goesP (h:t) (h1:t1)
  | h == h1 = True   -- Seems legit.
  | t == t1 = True   -- Er... this checks if the ENTIRE SUBLIST is equal.
  | otherwise False  -- Should be an equals sign here.

此外,如果其中一个列表为空,会发生什么?你只匹配非空案例。

如果你想“手动”(即不使用现有的库函数),你可能想要这样的东西:

goesP :: Domino -> End -> Bool
goesP []     _ = False -- Ran out of Dominos to check.
goesP (d:ds) e = hunt d e || goesP ds e
  where
    hunt d []     = False -- Run out of Ends to check.
    hunt d (e:es) = (d == e) || hunt d es

如果您想使用库函数执行此操作:

goesP :: Domino -> End -> Bool
goesP d e = any (`elem` d) e

点击Hoogle,找出原因。