lambdas: Creating a pair using pure functions

You can create a data structure that acts like a pair with associated functions first and second out of pure functions:

pair a b = \o -> o a b
first p = p (\a b -> a)
second p = p (\a b -> b)
-- Usage
p1 = pair 1 42
first p1 -- 1
second p1 -- 42

or:

(define (pair a b) (lambda (o) (o a b)))
(define (first p) (p (lambda (a b) a)))
(define (second p) (p (lambda (a b) b)))
; Usage
(define p1 (pair 1 42))
(first p1) ; 1
(second p1) ; 42

This seems kind of trivial but it shows how simple it is to create things that look like objects with state using closures... but don't push the "equivalence" too far! (closure-object equivalence).

Published on: 06 Jul 2024