An Anamorphism (from the Greek ἀνά "upwards" and μορφή "form, shape) over a type T is a function of type U → T that destructs the U in some way into a number of components. On the components that are of type U, it applies recursion to convert theme to T 's. After that it combines the recursive results with the other components to a T , by means of the constructor functions of T .
For example if we want to build List(N, N-1, …, 1) from N we would use anamorphism from Int to List[Int]. It’s the opposite operation to fold - unfold.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ListAnamorphism[U, T] = U => List[T] | |
def listAnamorphismFactory[U, T](func: T => Option[(U, T)]): ListAnamorphism[T, U] = { | |
in: T => | |
def ana(initial: T): List[U] = func(initial) match { | |
case None => Nil | |
case Some((current, next)) => current :: ana(next) | |
} | |
ana(in) | |
} | |
val listDestruct: ListAnamorphism[Int, Int] = listAnamorphismFactory { i: Int => if (i == 0) None else Some(i, i - 1) } |
No comments:
Post a Comment