A useful technique: partial defunctionalization

Yes exactly. So a simple example would be:


add1 : Int -> Int 
add1 = (+)

double : Int -> Int 
double n = 2 * n

calculate : Int -> Int
calculate n = add1 (double n)

turns into

type Op 
    = Add1
    | Double 

calculation : List Op
calculation = 
     [Double, Add1]

evaluate : Int -> List Op -> Int
evaluate = List.foldl eval

eval : Op -> Int -> Int
eval op inp =
     case op of
          Add1 -> inp + 1
          Double -> inp * 2

calculate : Int -> Int
calculate n = 
    evaluate n calculation

The second version represents the computation as data and deffers the evaluation to a later stage.

2 Likes