dopatraman
dopatraman

Reputation: 13908

Map a function over a string

My understanding is that a String in Haskell is a list of Characters. So I should be able to map a function Char -> Whatever over a string, right?

testChar :: Char -> String
testChar c = c:c:[]

myFunc :: String -> String
myFunc str = map testChar str

main = do
    putStrLn $ myFunc "hi"

When I run this i get:

 Couldn't match type ‘[Char]’ with ‘Char’
    Expected type: Char -> Char
      Actual type: Char -> String
    In the first argument of ‘map’, namely ‘testChar’
    In the expression: map testChar str

What am i doing wrong here?

Upvotes: 3

Views: 6099

Answers (2)

Chris Martin
Chris Martin

Reputation: 30756

ghci is your friend:

Prelude> let testChar c = c:c:[]
Prelude> let myFunc str = map testChar str
Prelude> :t myFunc
myFunc :: [a] -> [[a]]
Prelude> myFunc "abc"
["aa","bb","cc"]

Contrast with:

Prelude> let myFunc' str = concatMap testChar str
Prelude> :t myFunc'
myFunc' :: [b] -> [b]
Prelude> myFunc' "abc"
"aabbcc"

Various equivalent ways to write this function:

myFunc' str = concatMap testChar str
myFunc' = concatMap testChar
myFunc' str = str >>= testChar
myFunc' = (>>= testChar)

Upvotes: 10

Louis Wasserman
Louis Wasserman

Reputation: 198481

testChar :: Char -> String
testChar c = c:c:[]

myFunc :: String -> String
myFunc str = map testChar str

These two do not make sense. testChar maps a Char to a different type, and you expect map to map that function and get the same type out the other side? myFunc will actually return a [[Char]], not a [Char]/String.

Perhaps you meant concatMap?

Upvotes: 4

Related Questions