Skip to content

Instantly share code, notes, and snippets.

@akihiro4chawon
Created January 6, 2012 12:46
Show Gist options
  • Save akihiro4chawon/1570459 to your computer and use it in GitHub Desktop.
Save akihiro4chawon/1570459 to your computer and use it in GitHub Desktop.
Ken が凄すぎる。。。
import com.github.okomok.ken
object ArrowLoopFib extends ken.Main {
import ken._
import List.{tail, zipWith}
import Tuple2.snd
val fibSeqFrom = locally {
// use Function Arrow in this environment
import Function.{app, loop, &&&:, ***:, <<<:, >>>:}
val `(.)` = `op_.`[Lazy[List[Int]], Lazy[List[Int]], Lazy[List[Int]]]_
val `(:)`: Int => Lazy[List[Int]] => Lazy[List[Int]] = List.op_::[Int]_
val `((.).(:))` = `(.)` `.` `(:)`
val tupleToHeads = (`((.).(:))` ***: `(:)`) >>>: app
val sumAdjacentTerms = (Lazy.liftM2(zipWith[Int, Int, Int](Int.op_+))_ &&&: Lazy.liftM(tail[Int])_) >>>: app
val fibLoop = tupleToHeads ***: sumAdjacentTerms >>>: app
loop(fibLoop.&&&:(snd _)) // Dont be confused with `fibLoop &&&: (snd _)`!
// The expression above is equivalent to the below except that type inference works.
// `loop(snd[Lazy[List[Int]]]_ &&&: fibLoop)`
}
override def main_ = {
// use Kleisli Arrow in this environment
val kio = Kleisli._asArrow[IO]
import kio.{arr, >>>:}
val printFirst100FibNumFrom =
arr(fibSeqFrom) >>>: arr(List.take[Int](100)_) >>>: Kleisli(IO.print(_: List[Int]))
printFirst100FibNumFrom((0, 1))
}
// def main(args: Array[java.lang.String]) {
// val fibSeq = fibSeqFrom((0, 1))
// println(List.take(100)(fibSeq))
// }
}
import Control.Arrow
fibSeqFrom :: (Integer, Integer) -> [Integer]
fibSeqFrom = loop $ snd &&& fibLoop
where
fibLoop = app <<< tupleToHeads *** sumAdjacentTerms
sumAdjacentTerms = app <<< zipWith (+) &&& tail
tupleToHeads = app <<< ((.).(:)) *** (:)
main :: IO()
main = runKleisli printFirst100FibNumFrom $ (0, 1)
where
printFirst100FibNumFrom = arr fibSeqFrom >>> arr (take 100) >>> Kleisli print
@okomok
Copy link

okomok commented Jan 6, 2012

Arrowは(inferenceが弱くて)苦しいんですよね・・・
Monadあたりまでは何とかなるんですが・・・

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment