Make our own typeclass
In this chapter, we will create a toy typeclass to practice what we've learned so far for fun.
define our own typeclasses
The typeclass has a behavior to always reverse anything:
class Reversible a where
reverseIt :: a -> a
make instances of our typeclass
Int
instance Reversible Int where
reverseIt = negate
Boolean
instance Reversible Boolean where
reverseIt true = false
reverseIt false = true
String
import Data.String as String
instance Reversible String where
reverseIt = String.fromCodePointArray <<< Array.reverse <<< String.toCodePointArray
Array a
import Data.Array as Array
instance Reversible (Array a) where
reverseIt = Array.reverse
custom ADT
data Direction = North | East | South | West
instance Show Direction where
show North = "North"
show South = "South"
show East = "East"
show West = "West"
instance Reversible Direction where
reverseIt North = South
reverseIt South = North
reverseIt East = West
reverseIt West = East
Run it in REPL
> reverseIt 23
-23
> reverseIt false
true
> reverseIt "Hello!"
"!olleH"
> reverseIt [12, 13, 14]
[14,13,12]
> reverseIt North
South
> reverseIt 25.0
Error found:
in module $PSCI
at :1:1 - 1:15 (line 1, column 1 - line 1, column 15)
No type class instance was found for
Reversible.Reversible Number