Skip to content

Instantly share code, notes, and snippets.

View mbrandonw's full-sized avatar

Brandon Williams mbrandonw

View GitHub Profile
@mbrandonw
mbrandonw / transducer-type.swift
Last active October 18, 2020 16:56
How to get a transducer type without higher kinds
import Foundation
// A bunch of convenience things
func const <A, B> (b: B) -> A -> B {
return { _ in b }
}
func repeat <A> (n: Int) -> A -> [A] {
return { a in
return map(Array(1...n), const(a))
}
@mbrandonw
mbrandonw / tuples.swift
Created December 24, 2014 16:49
Named tuples in Swift
func minmax (a: Int, b: Int) -> (min: Int, max: Int) {
return (min(a, b), max(a, b))
}
minmax(10, -2) //=> (.0 -2, .1 10)
minmax(10, -2).min //=> -2
minmax(10, -2).max //=> 10
func unit <A, B> (f: A -> () -> B) -> (A -> B) {
return { a in
return f(a)()
}
}
/*:
Brandon Williams
# Lenses in Swift
*/
/*:
## i.e. Functional getters and setters
protocol LensType {
typealias Whole
typealias Part
var get: Whole -> Part { get }
var set: (Part, Whole) -> Whole { get }
}
struct Lens <A, B> : LensType {
typealias Whole = A
@mbrandonw
mbrandonw / lens-functorial.swift
Created January 17, 2016 18:22
Making `Lens<Whole, Part>` into a functor
struct Lens<A, B> {
let get: A -> B
let set: (B, A) -> A
func map <C> (f: B -> C) -> Lens<A, C> {
return Lens(
get: { f(get($0)) },
set: { set(f($0), $1) }
)
}
@mbrandonw
mbrandonw / file.swift
Created February 2, 2016 21:41
Swift compiler bug?
// In Parent.swift
struct Parent {
}
// In Child.swift
extension Parent {
struct Child {
}
}
@mbrandonw
mbrandonw / bug.swift
Last active April 1, 2017 14:27
Swift bug with extending generic typealiases?
struct F<A, B> {
let f: (A) -> B
}
typealias G<A> = F<A, Int>
extension G {
func something(a: A) -> Int {
return self.f(a)
// ^--- error: cannot convert return expression of type 'B' to return type 'Int'
class Function<B> {
func call<A>(_ a: A) -> B {
fatalError("unimplemented")
}
}
final class PrintInt: Function<Void> {
func call(_ a: Int) -> Void {
print(a)
}
class Function<B> {
func call<A>(_ a: A) -> B {
fatalError("unimplemented")
}
}
final class PrintInt: Function<Void> {
func call(_ a: Int) -> Void {
print(a)
}