Scalaの記事です。Haskellはあまり書けません。
Iterateeの複雑さから開放されたいのでPipe系ライブラリ使いましょうという記事です。
Iterateeとの比較や簡単な使い方についてつらつらと書いていきます。
| package disample | |
| case class DiSampleConfig(foo: Int, bar: String) | |
| object DiSampleConfig { | |
| implicit val configs: Configs[DiSampleConfig] = Configs { c => | |
| DiSampleConfig( | |
| foo = c.get[Int]("foo"), | |
| bar = c.get[String]("bar") | |
| ) | |
| } |
| import scala.annotation.StaticAnnotation | |
| import scala.reflect.macros.Macro | |
| import language.experimental.macros | |
| class body(tree: Any) extends StaticAnnotation | |
| trait Macros extends Macro { | |
| import c.universe._ | |
| def selFieldImpl = { |
| var daggy = require('daggy'), | |
| State = require('fantasy-states'), | |
| Cofree = require('fantasy-cofrees'), | |
| AST = daggy.taggedSum({ | |
| Add: ['l', 'r'], | |
| Sub: ['l', 'r'], | |
| Num: ['n'] | |
| }), | |
| incNode = State.get.chain(function(n) { | |
| return discard( |
| class A(private[this] var a: => Int){ | |
| lazy val b = a | |
| } |
| var State = require('fantasy-states'), | |
| Tuple2 = require('fantasy-tuples').Tuple2, | |
| // Tuple2 Number Number | |
| initial = Tuple2(0, 1), | |
| // State (Tuple2 Number Number) Number -> State (Tuple2 Number Number) Number | |
| next = discard( | |
| State.modify(function(t) { | |
| return Tuple2(t._1 + 1, (t._1 + 1) * t._2); |
| import scalaz._, Scalaz._ | |
| object MaxValue extends App { | |
| val a = Map(1 -> 10, 2 -> 5) | |
| val b = Map(2 -> 10, 3 -> 7) | |
| val c = a.mapValues(Tags.MaxVal) |+| b.mapValues(Tags.MaxVal) | |
| (c: Map[Int, Int]) assert_=== Map(1 -> 10, 2 -> 10, 3 -> 7) | |
| } |
| val m1 = Map(1 -> 2, 2 -> 5, 3 -> 1) | |
| val m2 = Map(2 -> 4, 3 -> 3, 4 -> 3) | |
| def toMultiMap[A, B](m1: Map[A, B], m2: Map[A, B]): Map[A, Set[B]] = | |
| (m1.toSeq ++ m2.toSeq).groupBy(_._1).mapValues(_.map(_._2).toSet) | |
| /* | |
| scala> toMultiMap(m1, m2).mapValues(_.max) | |
| res0: scala.collection.immutable.Map[Int,Int] = Map(2 -> 5, 4 -> 3, 1 -> 2, 3 -> 3) | |
| */ |
| import Data.Semigroup | |
| import Numeric.Natural.Internal | |
| -- 2x2 integer matrix [[a,b],[c,d]] | |
| data Mat2x2 a = Mat2x2 a a a a deriving (Show,Eq) | |
| -- multiply matrix [[a,b],[c,d]] . [[p,q],[r,s]] = [[a*p+b*r, a*q+b*s],[c*p+d*r, c*q+d*s]] | |
| multiply_mat2x2 :: Num a => Mat2x2 a -> Mat2x2 a -> Mat2x2 a | |
| multiply_mat2x2 (Mat2x2 a b c d) (Mat2x2 p q r s) = Mat2x2 (a*p+b*r) (a*q+b*s) (c*p+d*r) (c*q+d*s) |