How to make a nullary data constructor in Haskell return True for null -
i have algebraic data type, say
data tree = node (tree a) (tree a) | empty
i want null
return true
empty
node; false
otherwise.
for example,
> tree = empty > null tree
right now, gives following error.
<interactive>:261:1: error: • no instance (foldable tree) arising use of ‘null’ • in expression: null tree in equation ‘it’: = null tree
note null
return true
nothing
.
> null nothing true
null
requires instance of foldable
: null :: foldable t => t -> bool
the easiest way create instance of foldable
tree a
is:
{-# language derivefoldable #-} data tree = node (tree a) (tree a) | empty deriving foldable
or in ghci
:
λ > :set -xderivefoldable λ > data tree = node (tree a) (tree a) | empty deriving foldable λ > null empty true λ > null (node 1 empty empty) false
note: reason null
return true
nothing
because maybe
has instance of foldable
.
the long way:
instead of taking shortcut using haskell's magical extensions can write foldable
instance manually explained here, it's boils down to:
data tree = node (tree a) (tree a) | empty instance foldable tree -- minimal definition "foldmap" or "foldr", i'm choosing "foldr" -- foldr :: (a -> b -> b) -> b -> tree -> b foldr _ b empty = b foldr f b (node left right) = f (foldr f (foldr f b right) left)
Comments
Post a Comment