0

I'm writing a recursive function that takes a char as input, and removes the char from a string on output.

Eg: INPUT: abbacysa | OUTPUT: bbcys

I'm a beginner in Haskell so just trying to wrap my head around recursion still with practice.

I start out by creating the function with an empty list I then select the elements within the list and begin the condition guard. I looked into using drop but I think maybe there is a better way of doing this?

removeChar [] = []
removeChar (x:xs)
  | x `elem` "a" = removeChar drop "a"
1
  • 1
    removeChar = filter (/= 'a') Commented Aug 14, 2020 at 10:41

2 Answers 2

2

You start with base of recursion:

removeChar [] = []

If string is not empty, you have two possible options:

  1. It starts from a then you want to skip. So result is just rest of string without letter 'a'.
removeChar ('a':xs) = removeChar xs 
  1. It doesn't, then you want to keep it. So result is letter plus rest of string without letter 'a'.
removeChar (x:xs) = x: removeChar xs 
Sign up to request clarification or add additional context in comments.

1 Comment

Don't you mean, "If string is not empty"?
0

Here is a solution where you put in a string and a char you want to remove from the string.

Recursively:

removeChar :: String -> Char -> String
removeChar [] _ = []
removeChar (x:xs) n = if (x == n) then removeChar xs n
                 else x : removeChar xs n

First we check that char "x" in string (x:xs) equals char "n", if it does then we remove the character, else we keep on looping through the string.

Input: removeChar "abba baby" 'b'
Output: "aa ay"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.