Reputation: 11
How would I write a function that takes a list as an argument and returns a random element that is not a part of the list in Haskell?
randomElement [a", "b", "c"]
"z"-- returns any string except "a", "b", "c"
So far I've written a function that checks recursivly if an element is in a list.
inList _ [] = False
inList n (x:xs)
| x == n = True
| otherwise = inList x xs
However I don't know how to then modify this function or how to write an additional function that then returns an element that's not a member of the list.
Upvotes: 1
Views: 132
Reputation: 152707
Here is a solution based on the diagonalization argument that shows that String
is not countably infinite. Unlike the other proposed solutions, this one actually guarantees that it is different from any element in the list passed in, while still being lazy enough to work with infinite lists.
distinctHead :: String -> Char
distinctHead "" = 'a'
distinctHead ('a':_) = 'b'
distinctHead (c:_) = pred c
distinct :: [String] -> String
distinct = map distinctHead . zipWith drop [0..]
Upvotes: 1