2

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?

2 Answers 2

1

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)
1
  • I suggest you start off by repairing the OP's bug to properly connect everything up.
    – dfeuer
    Oct 25, 2020 at 16:49
1

By using recursion, it is done this way.

rmCharsRec :: String -> String -> String
rmCharsRec [] str = str
rmCharsRec (x:xs) str = rmCharsRec xs (rmChar x str)
6
  • Can you add an explanation of why this is better than the original poster's code? You and I know, but they may not. Also, this doesn't actually answer the question, because it doesn't connect to foldr.
    – dfeuer
    Oct 25, 2020 at 16:52
  • @dfeuer why is it better? we end up with the chain of filters anyway in both cases? whether we remove the 1st arg's leftmost char first, or last, is no real difference AFAICT.
    – Will Ness
    Oct 25, 2020 at 19:55
  • @WillNess, the code in the question is buggy. Try compiling with -Wall.
    – dfeuer
    Oct 25, 2020 at 19:57
  • @dfeuer I see the superficial issue with the non-exhaustiveness, which is not pertinent to the essence of what the OP is doing, and is easily fixed. so I'm looking past that.
    – Will Ness
    Oct 25, 2020 at 20:00
  • @WillNess, that's all I meant.
    – dfeuer
    Oct 25, 2020 at 21:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.