Vladyslav Babych February 2016

Type error in explicitly typed binding (Haskell)

I am writing a very simple function which transforms a string by replacing a certain combinations of characters into another. (e.g. "ab" to "a") I am a noob in Haskell, and I get error: "Type error in explicitly typed binding"

Could you please tell me what is the problem? Code:

transform :: String -> String
transform [] = []
transform [x] = x
transform (x:y:xs)
        | x == "a" && y == "b" = "a" ++ (transform xs)
        | x == "b" && y == "a" = "b" ++ (transform xs)
        | x == "b" && y == "b" = "a" ++ (transform xs)
        | x == "a" && y == "a" = "aaa" ++ (transform xs)

Thank you!

Answers


Chad Gilbert February 2016

In the final transform pattern, you are using string literals for "a" and "b" when they should be characters.

transform :: String -> String
transform [] = []
transform [x] = [x]
transform (x:y:xs)
        | x == 'a' && y == 'b' = "a" ++ (transform xs)
        | x == 'b' && y == 'a' = "b" ++ (transform xs)
        | x == 'b' && y == 'b' = "a" ++ (transform xs)
        | x == 'a' && y == 'a' = "aaa" ++ (transform xs)

Also, there was a bug in the second transform definition, where you needed to wrap x in brackets because it was returning a list of characters.

(You may also want to have a final pattern match to handle any other input, since you'll get a non-exhaustive error if you run this against a string like "zzz")

Post Status

Asked in February 2016
Viewed 3,249 times
Voted 14
Answered 1 times

Search




Leave an answer