Tuesday, 11 December 2018

Hylomorphism in 1 minute

Hylomorphism is  Catamorphism compose to Anamorphism function.

It's presented as 

Hylomorphism = catamorphism(anamorphism(x))
 or
Hylomorphism = fold(unfold(x))

Basically it constructs (unfold) complex type (like trees, lists) and destructs (folds) back into representing value.

For example to get factorial from N we can 
a) unfold N to list of (n),(n-1),..,0
b) fold with prod function the list from previous step.

And possible Scala example implementing function for getting factorial from N with help of previously introduced list's Catamorphism and  Anamorphism is:
type ListHylomorphism[U] = U => U
def listHylomorphism[U, T](cata: ListCatamorphism[T, U], ana: ListAnamorphism[U, T]): ListHylomorphism[U] = cata.compose(ana)
val factorial = listHylomorphism(prod, listDestruct)
assert(factorial(3) == 6)

No comments:

Post a Comment