Skip to content

Instantly share code, notes, and snippets.

@ukitaka
ukitaka / TypeClassLikeDecode.swift
Created April 26, 2017 06:21
型クラスライクなDecode.swift
typealias JSON = [String:String]
protocol Decoder {
associatedtype T
func decode(json: JSON) -> T
}
protocol Decodable {
static func decode<D: Decoder>(json: JSON, decoder: D) -> D.T where D.T == Self
}
@ukitaka
ukitaka / YCombinator.swift
Created March 24, 2017 03:16
YCombinator.swift
func fix<T, U>(_ f: @escaping (@escaping (T) -> U) -> (T) -> U) -> (T) -> U
{
return { f(fix(f))($0) }
}
let fib: (Int) -> Int = fix { f in { n in if n < 2 { return 1 } else { return f(n - 1) + f(n - 2) } } }
fib(1)
fib(2)
@ukitaka
ukitaka / SequenceProxy.swift
Last active February 26, 2017 01:40
SequenceProxy
public protocol SequenceProxy: Sequence {
associatedtype Element
var elements: [Element] { get }
}
public extension SequenceProxy {
func makeIterator() -> IndexingIterator<Array<Element>> {
return elements.makeIterator()
}
}
@ukitaka
ukitaka / PatternMatch.swift
Last active February 22, 2017 02:10
パターンマッチで網羅性を判断できない時がある @ Swift 3.0.2
let a = true
let b = false
let c = true
// MARK: - 2個のパターン
// OK
switch (a, b) {
case (true, _):
break
@ukitaka
ukitaka / lvalueTypeInf.scala
Created February 21, 2017 06:00
左辺からの推論.scala
def id[A](a: A): A = a
val eDouble1: Double = id(2.123345)
id(2) // Int
val eDouble2: Double = id(2)
@ukitaka
ukitaka / RealmTxn.swift
Last active February 17, 2017 11:24
Readerモナド + PhantomTypeでRealmの処理を再利用可能かつ合成可能にする
import RealmSwift
import Result
// MARK: -
public protocol _Read {}
public struct Read: _Read { }
public protocol _Write {}
public struct Write: _Write { }
@ukitaka
ukitaka / Applicative.scala
Last active February 14, 2017 02:13
ApplicativeとApplicativeの合成
trait Applicative[F[_]] extends Functor[F] {
// この2つが必要
def point[A](a: A): F[A]
def ap[A, B](a: F[A])(f: F[A => B]): F[B]
// pureはpointのalias?
def pure[A](a: A): F[A] = point(a)
// 以下はap/pointを使って実装できるもの
def apF[A,B](f: => F[A => B]): F[A] => F[B] = ap(_)(f)
@ukitaka
ukitaka / CovariantWorkaround.swift
Created February 13, 2017 09:30
自作の型でもFunctorであれば無理やりCovariantっぽく振舞わせることができる
enum Maybe<A> {
case some(A)
case none
func map<B>(_ f: (A) -> B) -> Maybe<B> {
switch self {
case .some(let a):
return .some(f(a))
case .none:
return .none
@ukitaka
ukitaka / Functor.scala
Created February 11, 2017 05:43
mapを使って実装できるもの
import scala.language.higherKinds
trait InvariantFunctor[F[_]] {
def xmap[A, B](fa: F[A])(f: A => B, g: B => A): F[B]
}
trait Functor[F[_]] extends InvariantFunctor[F] {
def map[A, B](fa: F[A])(f: A => B): F[B]
def xmap[A, B](fa: F[A])(f: A => B, g: B => A): F[B] = map(fa)(f)
@ukitaka
ukitaka / percent.swift
Created February 10, 2017 06:54
percentage postfix operator
postfix operator %
public postfix func %(int: Int) -> CGFloat {
return CGFloat(int) / 100.0
}
public postfix func %(int: Int8) -> CGFloat {
return CGFloat(int) / 100.0
}