Defining data with functions
So far, we looked at data types that take the values of other data types (both simple
or complex
). Since Haskell functions are also treated as first-class values, we can also use functions in our data type definition. In this recipe, we will define two data types that use functions as one of the field.
The first data type encapsulates a function f :: a -> b
, whereas the second data type is an interesting recursive structure.
Getting ready
Use the simple
stack template to create a new project called data-type-with-function
, and change into this directory:
stack new data-type-with-function simple
How to do it...
- Open
src/Main.hs
for editing. - Add a new data type
Func a b
to represent the functionf :: a -> b
:
newtype Func a b = Func (a -> b)
- Add a
compose
function. Thecompose
function takes in two functions and composes them together by giving an output of the first function to the next one:
compose :: Func a b -> Func b c -> Func a c ...