qwerty
qwerty

Reputation: 37

I want to check if any element of a list matches any element of other list Haskell

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

Upvotes: 1

Views: 250

Answers (1)

MathematicalOrchid
MathematicalOrchid

Reputation: 62808

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.

Upvotes: 2

Related Questions