0
votes

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"
2
removeChar = filter (/= 'a')Mark Seemann

2 Answers

2
votes

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 
0
votes

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"