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?

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

5
all (flip elem listx) input

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

1 Comment

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
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.

3 Comments

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
@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]"
Yup. There you are. 'and' is what you need to reduce [Bool] -> Bool.
4

One more way.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.