Dec. 31st, 2023

juan_gandhi: (Default)
(disclaimer: this is educational material)

  // Definitions for Boolean Logic
  const True  = x => y => x
  const False = x => y => y
  const Bool = b => b ? True : False

  // Definitions for pair and projection
  const p1 = x => y => x // did you notice? It's True
  const p2 = x => y => y // did you notice? It's False
  const Pair = x => y => f => f(x)(y)

  // Option constructors
  const None = Pair(True)("None")
  const Some = x => Pair(False)(x)

  // List constructors and operations
  const Nil = Pair(True)("Nil")
  const isEmpty = x => x(p1)
  const Head = z => z(p2)(p1)
  const HeadOption = z => z(p1)(None)(Some(z(p2)(p1)))
  const Tail = z => z(p2)(p2)
 
  const Cons = h => t => Pair(False)(Pair(h)(t))
  const Map = z => f => (isEmpty(z) (() => Nil) (() => Cons(f(Head(z))) (Map(Tail(z))(f))))()

  // visualizer

  const show = text => xs => {
    var buf = ""
    Map(xs)(x => buf += (x + ":"))
    println(`${text} ${buf}Nil`)
  }

  const Filter  = z => p =>
     (isEmpty(z) 
       (() => Nil) 
       (() => (p(Head(z)) (Cons(Head(z))(Filter(Tail(z))(p))) (Filter(Tail(z))(p))))
      )() // have to do it lazily

  // samples
  const ab = Cons("a")(Cons("b")(Nil))

  show("Expecting Nil ->")(Nil)
  show("Expecting a:b:Nil ->")(ab)

  const list1 = Cons(1)(Cons(-2)(Cons(3)(Cons(-4)(Nil))))

  show("three numbers")(list1)
  const isPositive = x => Bool(x > 0)

  show("squares")(Map(list1)(x => x*x))
  show("positives")(Filter(list1)(isPositive)) 

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

September 2025

S M T W T F S
 1 23456
78910111213
14151617181920
21222324252627
282930    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Sep. 4th, 2025 10:33 pm
Powered by Dreamwidth Studios