Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of an Fmap to distinguish from map?

My understanding is that the difference between map and fmap is that the latter can return a function?

I'm studying the functors section of this http://learnyouahaskell.com and some of the explanation is a bit unclear.

Map and fmap behave identically in the following:

let exMap = map (+1) [1..5]
let exFMap = fmap (+1) [1..5]

What is a good example of an fmap returning a function?

like image 249
Babra Cunningham Avatar asked Nov 30 '22 16:11

Babra Cunningham


1 Answers

No, the difference is that fmap applies to any functor. For instance:

readLine :: IO String           -- read a line
fmap length readLine :: IO Int  -- read a line and count its length

Just 4 :: Maybe Int
fmap (+10) (Just 4) :: Maybe Int  -- apply (+10) underneath Just
                                  -- returns (Just 14)

map turns a -> b into a function [] a -> [] b (usually written as [a] -> [b]).

fmap turns a -> b into a function f a -> f bfor any functor f, not only for f = []. The examples above chose f = IO and f = Maybe.

like image 138
chi Avatar answered Dec 05 '22 04:12

chi