views:

721

answers:

4

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?

+3  A: 

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.

Marcus Lindblom
yea, im new to haskell. I tried it out but I get an error.inputIndex :: [String] -> [String] -> BoolinputIndex [] _ = []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
@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
Yup. There you are. 'and' is what you need to reduce [Bool] -> Bool.
Marcus Lindblom
+2  A: 
all (flip elem listx) input

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

viraptor
thanks it worked. how exactly does it flow?thanks
pier
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
+5  A: 

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
+2  A: 

One more way.

import Data.Set
(fromList input) `isSubsetOf` (fromList listX)
Apocalisp