3

I have a 2 lists of strings
eg:

listx = ["name","age","rank"]
input = ["name","age"]

How can I compare the two lists to check whether the listx contains "name" & "age" given in input?

ephemient
  • 198,619
  • 38
  • 280
  • 391
pier
  • 503
  • 3
  • 14
  • 29

4 Answers4

6

B is a subset of A iff B \ A is empty

so another way to do it is

import Data.List ((\\))
null (input \\ listx)
newacct
  • 119,665
  • 29
  • 163
  • 224
5
all (flip elem listx) input

comes to mind. No idea how efficient it is though...

viraptor
  • 33,322
  • 10
  • 107
  • 191
  • 2
    you can also write it as "all (`elem` listx) input". @dlna: basically it expands to "all (\x -> x `elem` listx) input", which ensures that for every element of input, that it is an element of listx – newacct May 11 '09 at 20:41
4

Is this homework? :)

You need to create one or two recursive functions to walk through both lists, and search for every string in the input.

Or, you could look up some good functions in the Prelude that helps here.

Macke
  • 24,812
  • 7
  • 82
  • 118
  • 1
    yea, im new to haskell. I tried it out but I get an error. inputIndex :: [String] -> [String] -> Bool inputIndex [] _ = [] inputIndex listx input = [x `elem` listx |x <- input] error: - Type error in explicitly typed binding *** Term : inputIndex *** Type : [String] -> [String] -> [a] *** Does not match : [String] -> [String] -> Bool – pier May 11 '09 at 20:11
  • 1
    @dlna: your function is returning a list of Bools, one for each x. Whereas you just want one Bool, which is the logical and of all of them, so one thing you could do is "inputIndex listx input = and [x `elem` listx |x <- input]" – newacct May 11 '09 at 20:44
  • Yup. There you are. 'and' is what you need to reduce [Bool] -> Bool. – Macke May 13 '09 at 21:31
4

One more way.

import Data.Set
(fromList input) `isSubsetOf` (fromList listX)
Apocalisp
  • 34,834
  • 8
  • 106
  • 155