首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我想检查一个列表的任何元素是否与其他列表的任何元素相匹配

我想检查一个列表的任何元素是否与其他列表的任何元素相匹配
EN

Stack Overflow用户
提问于 2014-10-17 07:50:49
回答 1查看 222关注 0票数 1

模块Dominoes,其中

代码语言:javascript
复制
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

代码语言:javascript
复制
goesP :: Domino -> End -> Bool 
goesP (h:t) (h1:t1) 
  |   h == h1 = True
  |   t == t1 = True
  |  otherwise False
EN

回答 1

Stack Overflow用户

发布于 2014-10-17 16:42:25

代码语言:javascript
复制
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.

另外,如果这两个列表中的任何一个为空,会发生什么?您只匹配非空的案例。

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

代码语言:javascript
复制
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

如果要对库函数执行此操作,请执行以下操作:

代码语言:javascript
复制
goesP :: Domino -> End -> Bool
goesP d e = any (`elem` d) e

尝试一下Hoogle,看看为什么会这样。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26415759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档