0

i'am trying to create function that replace a given string in list of strings for exemple remplacer 'a' ["leaf","cacao"] gives a list ["le f","c co"]

with Haskell from this code :

remplacer k = map(\c -> if c== k then ' '; else c)

once i do the call

map remplacer "\r" ["abcd\r","alo\r"]

i got Couldn't match type 'char' with '[char]'

or result should be

["abcd ","alo "]
3
  • 1
    remPlacer is taking chars but you are using it on strings ([char]) Commented Oct 8, 2021 at 21:46
  • how do i need to change the code to let it accept strings? if i change it to : remplacer = map(\c -> if c== 'a' then ' '; else c) it works fine Commented Oct 8, 2021 at 21:48
  • You can't replace a String in a list of Strings with Haskell, lists are homogeneous. Commented Oct 9, 2021 at 0:52

1 Answer 1

3

Let's look at the types:

map                :: (a -> b) -> [a] -> [b]
"\r"               :: [Char] -- Which is equivalent to String
["abcd\r","alo\r"] :: [[Char]] -- Same as [String]
remplacer          :: Char -> [Char] -> [Char]

Notice remplacer takes Char, not [Char]. But replacing "\r" with '\r' alone won't work, because then we are making the first argument of map remplacer and the second '\r', in other words ((map remplacer) '\r') . This will not type check. What we want is make ramplacer '\r' the first argument:

λ> map (remplacer '\r') ["abcd\r","alo\r"]
["abcd ","alo "]

Edit: I couldn't resist exploring your how map remplacer ".." would work. For amusement, check how different of a function it is:

λ> :t map remplacer "ab"
map remplacer "ab" :: [[Char] -> [Char]]
λ>  ($  "abc") <$> (map remplacer ['a', 'b'])
[" bc","a c"]

$ is simply \f a -> f a, regular function application. The original question/answer uses map twice, this one uses map three times.

Sign up to request clarification or add additional context in comments.

12 Comments

i tried your solution i have got : lexical error in string/character literal at end of input
do you mean map (remplacer '\r') ["abcd\r","alo\r"]?
Edited the question with result I get in ghci.
i actually need to replace a string in list containing multiple strings. i don't know how your code can take do that. sorry im new with haskell
|

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.