Created
October 31, 2014 15:37
-
-
Save sjoerdvisscher/97106a4ff891593d85ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Semigroup { | |
func +(x: Self, y:Self) -> Self | |
} | |
extension String: Semigroup {} | |
extension Int: Semigroup {} | |
func foldMap1<A, M : Semigroup, S : SequenceType where S.Generator.Element == A>(t: S, f: A -> M) -> M? { | |
var g = t.generate() | |
if let x0 = g.next() { | |
var x = f(x0) | |
while let el = g.next() { | |
x = x + f(el) | |
} | |
return x | |
} else { | |
return nil | |
} | |
} | |
func concat1<M : Semigroup, S : SequenceType where S.Generator.Element == M>(t: S) -> M? { | |
return foldMap1(t, {$0}) | |
} | |
println(concat1(["Hello", " ", "world!"])) | |
struct FuncS<A, S: Semigroup> : Semigroup { | |
let value: A -> S | |
} | |
func +<A, S>(f: FuncS<A, S>, g:FuncS<A, S>) -> FuncS<A, S> { | |
return FuncS(value: { a in f.value(a) + g.value(a) }) | |
} | |
if let x = foldMap1([1,2,3], { a in FuncS(value: { b in a * b }) }) { | |
println(x.value(1), x.value(10)) | |
} | |
struct Dict<K: Hashable, V: Semigroup> : Semigroup { | |
let value: Dictionary<K, V> | |
} | |
func +<K, V>(a: Dict<K, V>, b: Dict<K, V>) -> Dict<K, V> { | |
var newDict = a.value | |
for (k, vb) in b.value { | |
if let va = a.value[k] { | |
newDict.updateValue(va + vb, forKey: k) | |
} else { | |
newDict.updateValue(vb, forKey: k) | |
} | |
} | |
return Dict(value: newDict) | |
} | |
var d: Dict<String, Int> = Dict(value: ["a":1, "b":2]) + Dict(value:["b":10, "c":20]) | |
println(d.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment