Functors: Identity, Composition, and fmap

https://news.ycombinator.com/rss Hits: 3
Summary

In writing software, we often encounter scenarios where a value resides within a context, a container of sorts. Standard function application, so straightforward with simple values, presents a challenge in these situations. Consider the Maybe data type in Haskell, which encapsulates the possibility of a value’s absence. Applying functions to values wrapped in Maybe requires a different approach, as direct function application results in a type error. For example, applying the function (+4) to the integer 2 is trivial: However, attempting to apply the same function directly to a Maybe wrapped value results in a type error: ghci> x = Just 2 ghci> (+4) x <interactive>:25:1: error: [GHC-39999] • No instance for ‘Num (Maybe Integer)’ arising from a use of ‘it’ • In the first argument of ‘print’, namely ‘it’ In a stmt of an interactive GHCi command: print it This is where fmap comes in. fmap provides a way to apply a function to a value within a wrapped context. In the case of Maybe, fmap allows us to apply (+4) to the integer inside a Just context: ghci> fmap (+4) (Just 2) Just 6 This leads us to the concept of Functors. The Functor typeclass in Haskell represents any type that can be mapped over. Lists, for example, are instances of the Functor typeclass. The definition of the Functor typeclass is as follows: class Functor f where fmap :: (a -> b) -> f a -> f b This typeclass defines only one function, fmap. This polymorphic function, works for any type constructor f that is an instance of the Functor typeclass. It takes : A function of type a -> b, which transforms a value of type a into a value of type b. A value of type f a, which represents a value of type a within a functorial context f. It then returns a value of type f b, which is a value of type b within the same functorial context f. Essentially, fmap applies the function to the value(s) inside the functorial context. As demonstrated earlier, we can use fmap (+4) (Just 2) because Maybe is a functor. fmap applie...

First seen: 2025-04-05 18:10

Last seen: 2025-04-05 20:10