Last active
February 8, 2017 05:00
-
-
Save rjsvaljean/ce415dee74e3bc4bffc8eba1384de56c to your computer and use it in GitHub Desktop.
type specific paramorphisms
This file contains hidden or 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
| def map[A, B](f: A => B)(as: List[A]): List[B] = { | |
| as match { | |
| case Nil => Nil | |
| case h :: t => f(h) :: map(f)(t) | |
| } | |
| } | |
| def fold[A, B](z: B)(f: (A, B) => B)(as: List[A]): B = { | |
| as match { | |
| case Nil => z | |
| case h :: t => f(h, fold(z)(f)(t)) | |
| } | |
| } | |
| def mapAsFold[A, B](f: A => B)(as: List[A]): List[B] = { | |
| fold[A, List[B]](Nil)((a, b) => f(a) :: b)(as) | |
| } | |
| def tails[A](as: List[A]): List[List[A]] = { | |
| as match { | |
| case Nil => Nil | |
| case h :: t => (h :: t) :: tails(t) | |
| } | |
| } | |
| def listpara[A, B](z: B)(f: ((A, List[A]), B) => B)(as: List[A]): B = { | |
| as match { | |
| case Nil => z | |
| case h :: t => f((h, t), listpara(z)(f)(t)) | |
| } | |
| } | |
| def tailspara[A](as: List[A]) = listpara[A, List[List[A]]](Nil)({case ((h, t), b) => (h :: t) :: b})(as) |
This file contains hidden or 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
| sealed trait Tree[A] | |
| case class Leaf[A](a: A) extends Tree[A] | |
| case class Branch[A](a: A, l: Tree[A], r: Tree[A]) extends Tree[A] | |
| def tailsT[A](as: Tree[A]): Tree[Tree[A]] = { | |
| as match { | |
| case l @ Leaf(_) => Leaf(l) | |
| case b @ Branch(_, l, r) => Branch(b, tailsT(l), tailsT(r)) | |
| } | |
| } | |
| def treepara[A, B]( | |
| lf: A => B)( | |
| bf: ((A, Tree[A]), B, B) => B)( | |
| as: Tree[A]): B = { | |
| as match { | |
| case Leaf(a) => lf(a) | |
| case b @ Branch(a, l ,r) => bf( | |
| (a, b), | |
| treepara(lf)(bf)(l), | |
| treepara(lf)(bf)(r) | |
| ) | |
| } | |
| } | |
| def tailsTpara[A](as: Tree[A]) = treepara[A, Tree[Tree[A]]]( | |
| l => Leaf(Leaf(l)))( | |
| {case ((a, t), l, r) => Branch(t, l, r)})(as) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment