Reputation: 23
I'm a beginner learning Haskell, and I'm trying to write a function that does the same thing as the following function (rmCharsRec) using foldr:
rmChar :: Char -> String -> String
rmChar char xs = filter (/=char) xs
rmCharsRec :: String -> String -> String
rmCharsRec [] (y:ys) = (y:ys)
rmCharsRec (x:xs) (y:ys) = rmChar x (rmCharsRec xs (y:ys))
I'm not quite sure how can I make the infixed function in foldr check each Char in the second string.
Or am I going in the wrong direction here?
Upvotes: 2
Views: 894
Reputation: 21
By using recursion, it is done this way.
rmCharsRec :: String -> String -> String
rmCharsRec [] str = str
rmCharsRec (x:xs) str = rmCharsRec xs (rmChar x str)
Upvotes: 1
Reputation: 476574
A foldr :: Foldable f => (a -> b -> b) -> b -> f a -> b
function basically replaces the (:)
function in the list with another function f
.
We thus can replace x1 : ( x2 : … : [] )
with f x1 (f x2 … (f xn z) … )
.
The base case is here thus the second list, and we use foldr
to each time call rmChar
for the given character and the result of folding the rest of the list.
rmCharsRec :: String -> String -> String
rmCharsRec xs ys = foldr rmChar ys xs
We here thus replace for example a list [x1, x2, x3, x4]
with rmChar x1 (rmChar x2 (rmChar x3 (rmChar x4 ys)))
.
We can generalize the functions and make these point-free to:
rmChar :: Eq a => a -> [a] -> [a]
rmChar = filter . (/=)
rmCharsRec :: (Foldable f, Eq a) => f a -> [a] -> [a]
rmCharsRec = flip (foldr rmChar)
Upvotes: 1