Haskell World logo Haskell WorldWrite code, build worlds
Programming

Haskell Deriving Strategies Explained for Real Types

A student pasted this into the class chat in the second week of the term: newtype UserId = UserId Int deriving (Eq, Ord, Show, ToJSON) , and the compiler refused it with a message about not being able to make a derived instance, followed...

A Haskell source file on screen showing a newtype declaration with separate stock and newtype deriving clauses beside compiler warnings

A student pasted this into the class chat in the second week of the term: newtype UserId = UserId Int deriving (Eq, Ord, Show, ToJSON), and the compiler refused it with a message about not being able to make a derived instance, followed by a suggestion to enable DeriveAnyClass. She enabled it. The code compiled. Three days later the API was sending {"unUserId": 41} where the front end expected 41, and nobody could find the line that caused it, because the line that caused it was a language pragma at the top of the file.

That is the whole problem with deriving in Haskell. The clause looks like one feature, and it is actually four different code generators competing for the same syntax. Which one GHC picks depends on which extensions happen to be on, and the one it picks when both are available is not always the one you wanted. Nine of my twenty four students hit some version of this before the first project was due, so I now teach the four strategies before I teach a single instance written by hand.

Four generators, one keyword

Since GHC 8.2 you can name the generator explicitly by turning on DerivingStrategies and writing the strategy keyword between deriving and the class list. There are four of them, and they produce genuinely different code.

StrategyWhere the code comes fromUse it forHow it bites
stockGHC has the algorithm built inEq, Ord, Show, Read, Functor, GenericOnly works for the dozen classes GHC knows
newtypeReuses the wrapped type's instanceNum, Semigroup, ToJSON on a newtypeInherits behaviour you may not want
anyclassThe class's own default methodsClasses designed with Generic defaultsSilently empty or Generic shaped output
viaAnother type's instance, coercedShared encodings, units, orderingsNeeds the representations to match

Write the keyword and the ambiguity disappears from the file. More usefully, it disappears from the code review, because the reader no longer has to scroll to the pragma block to know what deriving (ToJSON) means here.

The advice I tell students to ignore

GHC's own suggestion is to enable DeriveAnyClass, and most answers you find online repeat it. For a class like ToJSON it is the wrong fix most of the time.

Here is what the two choices actually do to that UserId. With newtype deriving, the generated instance is the Int instance, reused unchanged, so the value encodes as 41 and the wrapper is invisible on the wire. With anyclass deriving, GHC takes the class's default method, which in Aeson is written in terms of Generic, so it encodes the data structure: a record with one field, named after the accessor. Both compile. Both are correct Haskell. One of them changes your API contract.

The reason this is hard to debug is that nothing in the type signature records the decision. The behaviour lives in whichever extension was enabled last, and if both GeneralizedNewtypeDeriving and DeriveAnyClass are on, GHC picks anyclass and emits a warning only if you asked for warnings. So ask for them. Put -Wderiving-defaults and -Wmissing-deriving-strategies in your ghc-options, available since GHC 8.8, and the compiler starts telling you about every clause in the project that is making this choice on your behalf. On a codebase of about forty modules I expect somewhere between five and fifteen hits the first time, and most of them turn out to be fine once you look.

{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype UserId = UserId Int
 deriving stock (Show)
 deriving newtype (Eq, Ord, ToJSON, FromJSON)

Note that Show is deliberately on a different line with a different strategy. Stock Show prints UserId 41, which is what you want in a log or in GHCi. Newtype Show prints 41, which looks identical to a bare integer in a stack trace at three in the morning. Splitting the clause by strategy is not cosmetic.

Why newtype deriving is not automatically the safe answer

Inheriting the underlying instance is right for identifiers and wrong for quantities, and the difference is worth ten minutes of class time.

Take newtype Meters = Meters Double. Derive Num through the newtype strategy and you get addition, which you want, and multiplication, which you almost certainly do not: two meters times three meters is not six meters, and the compiler now cheerfully agrees that it is. The whole point of wrapping the type was to make that expression a type error. One line of deriving undid it.

My rule, and it has held up across four terms of grading, is that newtype deriving is safe when the wrapper means this value is an opaque token and dangerous when the wrapper means this value has a unit. Tokens want equality, ordering, hashing and serialisation, all inherited. Quantities want a hand written Semigroup or a deliberately narrow class, which is the same argument I made about newtype patterns that prevent production bugs and the reason the choice of operation matters so much when you look at Semigroup and Monoid in practice.

deriving via, for borrowing an instance on purpose

DerivingVia arrived in GHC 8.6 and it is the strategy students reach for last and should probably reach for second. It says: generate this instance by coercing through that other type, which already has the instance I want.

The case where it earns its keep is JSON encoding across a family of types. If six of your request types should all encode with the same field label modifier, you write one type with that instance and derive the other six via it, instead of writing six ToJSON instances that drift apart over a year of edits. We had exactly that drift in a student project last spring: two of five endpoints used camel case because someone wrote the instance by hand in March and the convention changed in April.

newtype SnakeJSON a = SnakeJSON a

newtype CreateOrder = CreateOrder Order
 deriving stock (Generic)
 deriving (ToJSON) via (SnakeJSON Order)

The requirement is that the two types are representationally identical, which is what Coercible checks. If they are not, the error you get mentions roles and representational equality, and it is one of the few GHC messages I still read twice.

Standalone deriving, for the clauses that will not fit

Sometimes the clause cannot live next to the type: the type is in another module, or the instance needs a constraint that the data declaration cannot express. StandaloneDeriving handles both, and it takes a strategy keyword the same way.

The common case in my class is a parameterised type where you want Show only for some arguments. Writing deriving instance Show (Tree Int) in the module where you need it is clearer than widening the original declaration, and it keeps the constraint visible at the use site instead of hidden in a library.

The thing to watch is that standalone clauses are easy to lose. Two of them in a file nobody reads, and the project has instances that appear from nowhere when you import a module. Keep them in the module that defines the type when you can, and when you cannot, leave a line in the module header saying why.

What to change this week

Add DerivingStrategies to the default extensions in your cabal file, add -Wmissing-deriving-strategies to the warnings, and build. Then walk the list from the top and write a keyword on every clause the compiler complains about. It took me about fifty minutes on a project with sixty types, most of which turned into deriving stock with no behaviour change at all. The two that were not stock were the interesting ones, and one of them was a bug that had been in production for five months.

I will not pretend this catches everything. A clause that already says newtype can still inherit an instance you would not have chosen, and no warning will tell you that. For those you need the type to mean something, and the review question is simply whether the wrapper is a token or a quantity.

FAQ

Do I need DerivingStrategies for a plain deriving clause?

No. Without it, deriving (Eq, Show) keeps working exactly as it always has, and GHC uses the stock algorithm. The extension only adds the ability to say which generator you mean, which is why turning it on project wide costs nothing.

Which strategy does GHC choose when several apply?

Stock wins if the class is one GHC knows and no strategy is written. Otherwise, with both relevant extensions enabled, anyclass is preferred over newtype, and -Wderiving-defaults tells you when that happened. That preference order is the source of most surprise encodings.

Is DeriveAnyClass ever the right answer?

Yes, for classes written specifically to be derived that way, where the default method is the intended implementation. Many effect and schema libraries are built on that assumption and document it. The mistake is using it on a class whose default happens to compile.

Can I mix strategies in one deriving block?

Not in one clause, but you can stack as many clauses as you like on a single type, which is the normal way to write it. Group by strategy, one line each, and the type declaration reads like a short list of decisions. More of these walkthroughs sit in the programming section.

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