If I had data and I wasn’t sure if this was an Integer or a String, but I wanted to apply (+1) to it, if its an integer great, but if its a String- do nothing, how would I handle this? Is this where Nothing comes in?
If I had data and I wasn’t sure if this was an Integer or
Share
Well, Haskell functions are strongly typed, which means they specify the types of their inputs and outputs. In order to even accept a value of multiple types in the first place, you need to use
Eitherto hold them within the same type. So, for example, if you want to receive either aStringor anInteger, then your function must have type:Then, the way you write your function is to pattern match on the
Eitherto see which type of value you received. You would write something like:So, the easiest way to do what you want is to only increment the number if it is an
Integer, but leave theStringuntouched. You would write it like this:If you ask the compiler to infer the type of the above function, you will get:
Haskell has a nice trick to avoid the above boilerplate, which is to use
fmapfrom theFunctorclass. This lets us automatically write functions on just theRighthalf of theEitherwhile completely ignoring whatever is in theLefthalf, like so:If we infer the type of the above function, it actually comes out to:
But in our case we can specialize the type by setting
atoIntegerandftoEither String:In other words,
Either Stringis one example of an instance of theFunctorclass, of which there are many.However, note that in order to use this function on integers or strings, you must first wrap them in
LeftorRightconstructors. For example, these will not type-check:But these will:
This means that if you had, say, a list of integers an strings, you would have to write it something like:
Notice that if you try to mix integers and strings within a list, you get a type error:
Then we could map
fover the first correctlistto get: