我想检查列表中的任何元素是否与其他列表Haskell的任何元素相匹配 [英] I want to check if any element of a list matches any element of other list Haskell

查看:86
本文介绍了我想检查列表中的任何元素是否与其他列表Haskell的任何元素相匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  type Domino = [(Int,Int)] 
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的任何元素是否匹配与任何元素的结束。如果它返回true,否则返回false

  goesP :: Domino  - >结束 - > Bool 
goesP(h:t)(h1:t1)
| h == h1 = True
| t == t1 = True
|否则False


解决方案

  goesP :: Domino  - >结束 - > Bool 
goesP(h:t)(h1:t1)
| h == h1 =真 - 看起来合法。
| t == t1 = True - 呃...这将检查整个SUBLIST是否相等。
|否则为假 - 在这里应该是等号。

另外,如果其中一个列表为空,会发生什么?你只能匹配非空的情况。



如果你想手动(即不使用现有库函数),你可能需要一些东西像这样:

  goesP :: Domino  - >结束 - > Bool 
goesP [] _ = False - 跑出Dominos检查。
goesP(d:ds)e = hunt d e || goP ds e
其中
hunt d [] =假 - 结束检查。
hunt d(e:es)=(d == e)||搜寻

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

  goesP :: Domino  - >结束 - > Bool 
goesP de = any(`elem` d)e

Hoogle 找出原因。


module Dominoes where

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

I want to check if any element of Domino matches with any element of End. Returning true if it does and false if it doesn't

goesP :: Domino -> End -> Bool 
goesP (h:t) (h1:t1) 
  |   h == h1 = True
  |   t == t1 = True
  |  otherwise False

解决方案

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.

Also, what happens if either of the lists is empty? You're only matching the non-empty case.

If you want to do this "by hand" (i.e., without using existing library functions), you probably want something like this:

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

If you want to do this with library functions:

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

Have a go at hitting Hoogle to find out why that works.

这篇关于我想检查列表中的任何元素是否与其他列表Haskell的任何元素相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆