Haskell World logo Haskell WorldWrite code, build worlds
Programming

Haskell Functor and Applicative Explained With Real Code

You have a value stuck inside a Maybe, a list, or an IO action, and you keep writing case expressions just to apply one small function to it. Then you need to combine two of those wrapped values and the nesting gets worse.

A developer's laptop on a wooden desk showing Haskell code in a dark editor beside a notebook with hand drawn arrows between boxes

You have a value stuck inside a Maybe, a list, or an IO action, and you keep writing case expressions just to apply one small function to it. Then you need to combine two of those wrapped values and the nesting gets worse. Haskell Functor and Applicative exist to remove exactly that boilerplate, and once the two type classes click, a lot of real code gets shorter and easier to read.

This guide skips the box metaphors. It shows what the classes require, what the compiler gives you for free, and where each one fits in everyday code such as config parsing and form validation.

What the Haskell Functor class actually promises

A Functor is any type constructor f with one operation: fmap, which takes a function from a to b and turns an f a into an f b. That is the whole interface. For Maybe, fmap applies the function if there is a Just and leaves Nothing alone. For lists, it is map. For IO, it runs the action and transforms the result.

So fmap (+1) (Just 41) gives Just 42, fmap (+1) Nothing gives Nothing, and fmap length getLine gives an IO action that reads a line and returns its length. The infix form of fmap, written with a dollar sign between angle brackets, is the same function with nicer spacing in long pipelines.

The important thing is what fmap cannot do. It cannot change the shape. A list of 3 elements stays a list of 3 elements. A Nothing stays a Nothing. A Left error in an Either stays that exact Left. If you need to drop elements, short circuit, or decide on the next step based on a value, you are past Functor territory.

The two laws, in plain terms

Every Functor instance should obey two rules. Mapping the identity function changes nothing, and mapping two functions one after the other is the same as mapping their composition once. These laws are why you can refactor fmap f . fmap g into fmap (f . g) without fear.

Where Functor shows up in real code

Most production Haskell uses fmap constantly without anyone thinking of it as theory. Some common cases:

  • Reading an environment variable and parsing it: fmap read over the result of a lookup, or better, fmap readMaybe so a bad value becomes Nothing instead of a crash.
  • Transforming a database row after a query: fmap toUser over an IO of a list, which is really fmap inside fmap.
  • Adjusting a Map in one pass. Data.Map is a Functor over its values, so fmap applies a price increase of 5 percent to every entry while keeping all keys.
  • Working with Either for errors. fmap only touches the Right side, which matches the pattern described in our guide on Haskell Either for error handling without exceptions.

Applicative, for combining independent values

Functor handles one wrapped value. Applicative handles several that do not depend on each other. It adds two pieces: pure, which lifts a plain value into the context, and an apply operator that takes a wrapped function and a wrapped argument. In practice most people use liftA2 or the apply operator chained after fmap.

Say you parse a host and a port separately, each as a Maybe. With pattern matching you need a nested case with four branches. With Applicative you write liftA2 Config parsedHost parsedPort. If both are Just, you get Just a Config. If either is Nothing, you get Nothing. For a record with 6 fields, the applicative style is one line per field instead of a staircase of indentation.

Validation that reports every error

Here Applicative pays rent. A signup form has a name, an email, and an age. If you validate with Either, the first failure stops everything and the user fixes one error per submit. If you use a Validation type (from the validation or either package), whose Applicative instance accumulates errors in a list, a single pass returns all three problems at once.

That accumulation is only possible because Applicative cannot see intermediate results. Each field is checked on its own, so the instance is free to run every check and collect failures. A Monad, by contrast, lets the next step depend on the previous value, which forces it to stop at the first failure.

Applicative versus Monad, a counter take

A lot of tutorials teach Monad first and treat Applicative as a footnote. That ordering makes people reach for do notation even when their steps are independent, and it costs them real features.

The pushback: start with the weakest abstraction that works. If none of your steps needs the result of an earlier step, write it applicatively. You get error accumulation with Validation, potential parallelism in libraries such as Haxl, and parsers in optparse-applicative that can print a full help screen because the structure is known before anything runs. A monadic command line parser could not do that, since later options might depend on earlier values.

When you do need dependency, for example looking up a user and then fetching that user's orders, a Monad is the right tool. Our walkthrough on understanding monads in Haskell without the metaphors covers that step. The point is that do notation should be a choice, not a reflex. GHC's ApplicativeDo extension even rewrites independent do blocks into applicative form for you.

Traverse, the payoff of both classes

Once Functor and Applicative make sense, traverse becomes the most useful function in the Prelude. It walks a structure, applies a function that returns a wrapped value, and flips the result inside out.

Concretely, traverse readMaybe ["1","2","3"] gives Just [1,2,3], while traverse readMaybe ["1","x","3"] gives Nothing. One bad element fails the whole batch, with no manual loop. Swap Maybe for IO and traverse fetchUser userIds runs 50 fetches and returns a list of 50 users. Swap it for Validation and you get every parse error in a list of strings.

The rule of thumb: if you are writing mapM, sequence, or a fold that builds a Maybe of a list, traverse probably expresses it more clearly. It needs only Applicative, so it works with more types than mapM historically did.

Writing your own instances

For most data types you never write fmap by hand. Turn on DeriveFunctor (enabled by default in GHC2021) and add deriving Functor to a type with a trailing type parameter. A Tree a, a Response a, or a parser result all derive cleanly.

Applicative instances need more care, because pure and the apply operator must satisfy four laws, and there can be more than one sensible instance. Lists have the combination instance and ZipList has the pairwise one. If you write a custom instance, test the laws with QuickCheck on small random inputs; 100 cases per law catches most mistakes in under a second.

If wrapped values still feel strange, it helps to revisit how the Maybe type replaces null in Haskell, since Maybe is the friendliest Functor to practice on.

Frequently asked questions

What is the difference between Functor and Applicative in Haskell?

Functor lets you apply a plain function to one wrapped value with fmap. Applicative adds pure and the ability to combine several independent wrapped values, such as two Maybe fields into one record. Every Applicative is a Functor, but not every Functor can be an Applicative.

Is every Monad an Applicative?

Yes. Since GHC 7.10 the class hierarchy requires every Monad instance to also be an Applicative and a Functor. In practice this means anything you can use in do notation also works with fmap, liftA2, and traverse.

When should I use Applicative instead of do notation?

Use Applicative when none of your steps needs the result of an earlier one. You gain error accumulation, clearer intent, and sometimes parallel execution. Switch to do notation only when a later step genuinely depends on a value produced earlier.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Programming

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto