Functors, Monads, Applicatives – can be so simple | de.velopmind | The Det about Programming
補足説明を加えて簡単に整理してみた。
(A => B) => (C[A] => C[B])
(A => C[B]) => (C[A] => C[B])
trait Monoid[A] { | |
def mempty: A | |
def mappend(x: A, y: A): A | |
def mconcat(xs: Seq[A]): A = xs.foldLeft(mempty)(mappend) | |
} | |
object MonoidTest { | |
def sum[A: Monoid](xs: A*): A = implicitly[Monoid[A]].mconcat(xs) | |
implicit def numericMonoid[A: Numeric] = new Monoid[A] { |
import scala.annotation.tailrec | |
object Fibonacci { | |
@tailrec | |
def fibo(i: Int, prev: BigInt = 1, curr: BigInt = 0): BigInt = i match { | |
case 0 => 0 | |
case i if i < 2 => prev + curr | |
case _ => fibo(i - 1, curr, prev + curr) | |
} |
Functors, Monads, Applicatives – can be so simple | de.velopmind | The Det about Programming
補足説明を加えて簡単に整理してみた。
(A => B) => (C[A] => C[B])
(A => C[B]) => (C[A] => C[B])
module MonadTransformers where | |
import Control.Monad.Trans.Class | |
import Control.Monad.Trans.Maybe | |
data User = User { | |
id' :: Int, | |
firstName :: Maybe String, | |
lastName :: Maybe String | |
} deriving Show |
(ns random-alphanumeric-generator) | |
(def alphanumeric "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890") | |
(defn rand-alphanumeric [len] | |
(repeatedly len #(rand-nth alphanumeric))) | |
(->> (repeatedly #(rand-alphanumeric 5)) | |
(filter (fn [[a _ _ _ b]] (= a b))) | |
(map #(apply str %)) |
;;;; cf. http://riktor.hatenablog.com/entry/2012/07/20/224806 | |
(defn fib [n] | |
(if (or (= n 0) (= n 1)) | |
1 | |
(+ (fib (- n 1)) | |
(fib (- n 2))))) | |
(let [memo (atom {})] | |
(defn fib-memoized [n] |
import scala.collection.mutable.ListBuffer | |
val messageBoxes = Array.fill(3)(ListBuffer[String]()) | |
messageBoxes(0) += "message1" | |
messageBoxes(0) += "message2" | |
messageBoxes(0) += "message4" | |
messageBoxes(0) += "message5" | |
messageBoxes(1) += "message1" | |
messageBoxes(1) += "message2" | |
messageBoxes(1) += "message3" |
;;;; cf. http://riktor.hatenablog.com/entry/2012/07/22/223937 | |
(def counter | |
(let [cnt (atom 0)] | |
(fn [] (swap! cnt inc)))) | |
(counter) | |
(counter) | |
(counter) |
;;;; cf. http://riktor.hatenablog.com/entry/2012/07/25/001118 | |
(first '(1 2 3)) | |
(first '((1 2 3) 4 5 6)) | |
(rest '(1 2 3)) | |
(rest '(1 2 (3 4 5))) | |
(cons 1 '(2 3)) | |
(cons '(1 2 3) '((4 5 6))) | |
(cons 1 nil) |