Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map function in Haskell

Tags:

haskell

map

As far as I understand map in Haskell takes a function and a List and applies that function to every element in that list before creating a new list with the function applied to each member.

Trying it out, this works fine with really simple functions like (+5) so it works fine if I type:

map (+7) [2,8,9,3]

I get:

[9,15,16,10]

However this doesn't work with functions that I have created. Say I have made a function shiftLetter whose type declaration is:

shiftLetter :: Char -> Int -> Char

(with Int shifting how far along the letter returned is)

If I make a new function to do it with more than one letter and type:

shiftLetters :: String -> Int -> Char
shiftLetters letters shift = map shiftLetters "AKHLKHN"

I get errors, why is this?

like image 251
Eddie Avatar asked Oct 12 '13 19:10

Eddie


1 Answers

If you check the type of the map function then you see:

map :: (a -> b) -> [a] -> [b]

So you need a function that takes one parameter, but yours takes two. You have to use

shiftLetters letters shift = map (flip shiftLetter $ shift) letters

or

shiftLetters letters shift = map (`shiftLetter` shift) letters

Pointless style:

shiftLetters = flip $ map . flip shiftLetter
like image 63
Hauleth Avatar answered Sep 22 '22 23:09

Hauleth