Skip to content

Instantly share code, notes, and snippets.

@to4iki
to4iki / monoid.swift
Created September 13, 2015 12:35
swift monoid like scala
// http://gakuzzzz.github.io/slides/lets_play_with_loop
// http://qiita.com/S_Shimotori/items/abfb3eb15f3575a25466
struct Product {
let id: Int
let name: String
}
struct Item {}
struct Code {}
@to4iki
to4iki / List.swift
Last active January 5, 2016 23:29
List
import Foundation
// http://safx-dev.blogspot.jp/2015/07/swift-enum.html
// http://qiita.com/kazuhei0108/items/ece54ede8bdd9ab21ed8
// http://qiita.com/koher/items/ad6ce3624cbb529d9197
public indirect enum List<T> {
case Nil
case Cons(head: T, tail: List<T>)
}
@to4iki
to4iki / Result.swift
Last active September 1, 2015 11:58
Result<T, NSError>
// https://github.com/JaviSoto/Blog-Posts
enum Result<T> {
case Value(T)
case Error(NSError)
func map<U>(f: T -> U) -> Result<U> {
switch self {
case let .Value(x): return Result<U>.Value(f(x))
case let .Error(e): return Result<U>.Error(e)
}
@to4iki
to4iki / proc.rb
Created August 29, 2015 08:26
proc
def calc(b)
b.call(3, 2)
end
#def calc(&block)
# block.call
#end
# calc { |a, b| p a+b }
@to4iki
to4iki / array_extension.js
Last active August 29, 2015 14:27
es6 Array.prototype
const p = x => console.log(x);
function decompose(xs) {
return (xs.length > 0) ? { head: xs[0], tail: extract(xs, 1, xs.length-1) } : null;
}
function extract(xs, from, to) {
let r = [], i = from;
for (i; i <= to; i++) {
r.push(xs[i]);
@to4iki
to4iki / stream.js
Last active August 29, 2015 14:27
es6 Generator
// use babel
function* stream() {
let i = 0;
while (true) yield i++;
}
stream.prototype.take = function*(n) {
let i = 0;
let iter = this[Symbol.iterator]();
let e = iter.next();
@to4iki
to4iki / curry.js
Created August 15, 2015 04:13
curry + partial
// http://xraingardenx.com/js-curry-partial/
Function.prototype.curry = function() {
var fn = this,
args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply( this, args.concat(Array.prototype.slice.call(arguments)) );
};
};
@to4iki
to4iki / fibonacci.scala
Created August 1, 2015 15:04
fibonacci sequence
// http://lizan.asia/blog/2012/12/11/scala-competitive/
object Main {
def main(args: Array[String]): Unit = {
val sc = new java.util.Scanner(System.in)
val n = sc.nextInt
val list = List.fill(n)(sc.nextInt)
for (i <- list) {
println(fib(i).toString().takeRight(3).toInt)
}
@to4iki
to4iki / Square.swift
Created July 19, 2015 07:58
Square@swift
infix operator ** { associativity left }
func ** (rhs: Int, lhs: Int) -> Int {
return Array(1..<lhs).reduce(rhs) { (x, y) -> Int in x * rhs }
}
Array(1...5).map { 2 ** $0 }
// [2,4,8,16,32]
@to4iki
to4iki / Option+Extension.swift
Last active August 29, 2015 14:25
OptionalExtension@swift
extension Optional {
func reduce<U>(initial: U, combine: (U, T) -> U) -> U {
if let me = self {
return combine(initial, me)
} else {
return initial
}
}
func each(f: T -> Void) {