Skip to content

Instantly share code, notes, and snippets.

View mbrandonw's full-sized avatar

Brandon Williams mbrandonw

View GitHub Profile
struct Foo<A> {
// here `A` is a whole new type parameter, different from the above `A`
func bar<A>() -> Foo<A> {
return Foo<A>()
}
}
let x = Foo<Int>()
// There's a natural way to lift a predicate `(A) -> Bool` to a function `(A) -> A?
func optionalBool<A>(_ p: @escaping (A) -> Bool) -> (A) -> A? {
return { p($0) ? .some($0) : nil }
}
// There's a natural way to lift a predicate `(A) -> Bool` to a function `(A) -> Either<A, A>
func eitherBool<A>(_ p: @escaping (A) -> Bool) -> (A) -> Either<A, A> {
// notice the similarities of this with `optionalBool`:
return { p($0) ? .right($0) : .left($0) }
}
import Foundation
func zip<A, B, R>(
_ f: @escaping ((A) throws -> R) throws -> R,
_ g: @escaping ((B) throws -> R) throws -> R,
with: (A, B) -> R
) throws -> R {
return try f { a in
try g { b in
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
URLSession.shared.dataTask(with: URL(string: "/")!) { data, response, error in
print(data) // nil
print(response) // nil
print(error) // some error
}
.resume()
// https://twitter.com/UINT_MIN/status/968524617714249729
struct Prism<A, B> {
let preview: (A) -> B?
let review: (B) -> A
}
extension Prism where A == String, B == Int {
static var toInt: Prism {
return Prism(preview: Int.init, review: String.init)
@mbrandonw
mbrandonw / lib.swift
Last active March 18, 2018 14:01
Functional setters using Swift key paths
// ----------------------------------------------------
// These 3 helpers is all you need to unlock functional
// setters for every field of every immutable struct.
// ----------------------------------------------------
// A generic way to a lift writable key path and a value to a setter function.
func set<A, B>(_ kp: WritableKeyPath<A, B>, _ b: B) -> (A) -> A {
return { a in
var a = a
a[keyPath: kp] = b
enum StringOrInt {
case string(String)
case int(Int)
}
func isInt(_ stringOrInt: StringOrInt) -> Bool {
switch stringOrInt {
case .string: return false
case .int: return true
}
{-# LANGUAGE EmptyCase #-}
data Never
absurd :: Never -> a
absurd a = case a of {}
main = do
putStrLn "It compiles!"
{-# LANGUAGE EmptyCase #-}
data Never
absurd :: Never -> a
absurd a = case a of {}
main = do
putStrLn "It compiles!"
class Never private constructor()
fun <A> absurd(never: Never): A {
when(never) {}
}
println("It compiles!")