Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Last active July 1, 2020 00:41
Show Gist options
  • Save abiodun0/7ac00fdc0fc05a383174f2c7c58ea483 to your computer and use it in GitHub Desktop.
Save abiodun0/7ac00fdc0fc05a383174f2c7c58ea483 to your computer and use it in GitHub Desktop.
cons car and cdr in swift
typealias LinkedList = ((Any, Any) -> Any) -> Any
typealias Cons = (Any, Any) -> LinkedList
typealias Result = (LinkedList) -> Any
let cons: Cons = { (x: Any, y: Any) in
{
(z: (Any, Any) -> Any) in z(x, y)
}
}
let car: Result = {
(z: ((Any, Any) -> Any) -> Any) in z {p, q in p}
}
let cdr: Result = {
(z: ((Any, Any) -> Any) -> Any) in z {p, q in q}
}
var each: ((Any, (Any) -> ()) -> ())!
each = { (x: Any, thing: (Any) -> ()) -> () in
if let x = x as? LinkedList {
thing(car(x))
return each(cdr(x), thing)
} else {
thing(x)
}
}
var each: ((Any, (Any) -> ()) -> ())!
each = {
if let x = $0 as? LinkedList {
$1(car(x))
each(cdr(x), $1)
}
print("we always got here")
$1($0)
}
each = { guard let x = $0 as? LinkedList else { return $1($0) }
$1(car(x))
each(cdr(x), $1)
}
func each(_ x: Any, _ thing: (Any) -> ()) -> () {
if let x = x as? LinkedList {
thing(car(x))
return each(cdr(x), thing)
} else {
thing(x)
}
}
car(cons(1, 2))
print(cdr(cons(1, cons(2, 3))))
print(car(cons(1, cons(2, 3)))) // => 1
print(cons)
each(cons(1, cons(2, 3)), { x in print(x) })
import Foundation
typealias LinkedList = ((Any, Any) -> Any) -> Any
typealias Cons = (Any, Any) -> LinkedList
typealias Result = (LinkedList) -> Any
var each: ((Any, (Any) -> ()) -> ())!
let cons: Cons = { (x: Any, y: Any) in
{
(z: (Any, Any) -> Any) in z(x, y)
}
}
let car: Result = { $0 {p, q in p} }
let cdr: Result = { $0 {$1} }
each = {
if let x = $0 as? LinkedList {
$1(car(x))
return each(cdr(x), $1)
}
print("we always got here")
$1($0)
}
each(cons(1, cons(2, 4)), { print($0) })
let external: (() -> Void) -> Void = { _ in () }
func takesTwoFunctions(first: (() -> Void) -> Void, second: (() -> Void) -> Void) {
first { first {} } // Error
second { second {} } // Error
first { second {} } // Error
second { first {} } // Error
first { external {} } // OK
external { first {} } // OK
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment