Reputation: 71
The objective is: Using foldr
, define a function remove which takes two strings as its arguments and removes every letter from the second list that occurs in the first list. For example, remove "first" "second" = "econd"
.
If this function took a single character and a string, I would do:
remove a xs = foldr (\x acc -> if x /= a then x : acc else acc) [] xs
But I can't figure out how I am supposed to do this with two strings. Thank you!
Upvotes: 2
Views: 721
Reputation: 1315
remove :: String -> String -> String
remove xs ys = foldr (condCons) "" ys
where
condCons l rs | l `notElem` xs = l : rs
| otherwise = rs
It is also allowed to discard the 'ys' paramenter:
remove :: String -> String -> String
remove xs = foldr (condCons) ""
where
condCons l rs | l `notElem` xs = l : rs
| otherwise = rs
Basically, condCons takes a character L and a string Rs. If L is not an element of xs, then it cons to Rs, otherwise leave Rs unchanged. foldr takes the condCons, the intial string "", and the second argument ys. L takes on each character of the string ys from right to left, building a new string from "" using the condCons binary operator.
Upvotes: 1
Reputation: 71
remove xs ys = foldr (\x acc -> if elem x xs then acc else x : acc) [] ys
yep.
Upvotes: 5