What is the FlexibleContexts extension good for? Could you please explain it using a simple example?

Without FlexibleContexts all typeclass constraints on function definitions must have type variables. For example:

add :: Num a => a -> a -> a 
add = (+)

Where a is the type variable. With FlexibleContexts enabled you can have any type inside a typeclass.

intAdd :: Num Int => Int -> Int -> Int 
intAdd = (+)

This example is pretty contrived but it is the simplest I can think of. FlexibleContexts is usually only used with MultiParamTypeClasses. Here is an example:

class Shower a b where
  myShow :: a -> b

doSomething :: Shower a String => a -> String
doSomething = myShow

Here you can see we say that we only want a Shower a String. Without FlexibleContexts String would have to be a type variable instead of a concrete type.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)