Vladyslav Babych
Vladyslav Babych

Reputation: 123

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!

Upvotes: 1

Views: 132

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

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")

Upvotes: 3

Related Questions