right now I'm trying to make a function that can see if the input item is already in list, here's my code.
list :: [String]
list = ["a","b"]
listCheck :: String -> [String]
listCheck item = [(x:xs)| (x:xs) <- list, x == item]
the current problem is that it can only filter if the input is a character and not a string, when I left the type undeclared Haskell made the function Char -> [String], and it worked perfectily fine, it returned an empty list when it wasn't included and it returned a list with the item in it if it was included. When I added the String -> [String] it returned this error.
Couldn't match type `[Char]' with `Char'
Expected: Char
Actual: String
I tried to change it to x <- item and it compiled but it just gave [item, item] every time. I want to know what I can do to make it work with strings instead of chars, thank you.
CodePudding user response:
This part makes x as char.
(x:xs) <- list
each element mapping like
["a","b"]
'a':[] => x = 'a', xs = []
'b':[] => x = 'b', xs = []
so, if you want to check element in list and get found one, how about below.
listCheck :: String -> [String]
listCheck item = [x| x <- list, x == item]
Prelude> listCheck "a"
["a"]
Prelude> listCheck "b"
["b"]
Prelude> listCheck "c"
[]
Prelude>
