Skip to content

Instantly share code, notes, and snippets.

@adam-nathan
adam-nathan / eulerian_tour.py
Created February 28, 2022 16:39
Eulerian tour algorithm
# Eulerian tour algorithm https://en.wikipedia.org/wiki/Eulerian_path
def eulerian_tour(root: TreeNode) -> List[TreeNode]:
tour = []
def dfs(node: TreeNode, depth: int) -> None:
tour.append((node.val, depth))
if node.left:
dfs(node.left, depth + 1)
tour.append((node.val, depth))
if node.right:
dfs(node.right, depth + 1)
@adam-nathan
adam-nathan / helpers.apl
Last active March 9, 2022 16:31
Useful functions in APL
segs ← ⊃,/∘(⍳∘≢,/¨⊂)
segs ← (⊃,/)⍳∘⊃∘⌽∘⍴,/¨⊂ ⍝ works for matrix also
freq ← ((⎕C ⎕A)∘.=⊢)
mseg ← {⎕IO←0 ⋄ (⍳∘≢⍵)∘.{⍺↓⍵},\⍵} ⍝ all subvectors in correct position
bits ← 2∘⊥⍣¯1
pdf←{
⍺←(0 1)
nom←*⍤-2÷⍨*∘2
denom←0.5*⍨○2
@adam-nathan
adam-nathan / Deriving the Y Combinator.md
Last active February 8, 2022 17:56
Deriving the Y Combinator

Recall that the definition of the Y combinator is

    x   = f x       -- fixed-point
    Y f = f (Y f)

The simplest recursion is

    x = x   -- [error: cannot reference a symbol before it is defined]

Create a function repeat that takes a function that calls itself.

@adam-nathan
adam-nathan / combinator-birds.hs
Created February 3, 2022 11:43
Combinator birds in Haskell
bluebird = s (k s) k
blackbird = bluebird bluebird bluebird
bunting = bluebird blackbird bluebird
becard = bluebird dove bluebird
cardinal = starling (dove starling) (kestrel kestrel)
dove = bluebird bluebird
dickcissel = bluebird dove
dovekies = dove dove
eagle = bluebird blackbird
@adam-nathan
adam-nathan / leet.dyalog
Last active July 18, 2022 13:02
leet in APL
q1920 ← {⎕IO←0 ⋄ (⊂⌷⊢)⍵}
q1672 ← ⌈/+/
q1431 ← {0≤⍺+⍵-⌈/⍵}
q1512 ← +/=/(((⊂∘↑⍸)(∘.<⍨⍳∘≢))⌷⊢)
q1470 ← {,⍉⍵⍴⍨2,2÷⍨⍴⍵}
q0771 ← +/∊jewels ∘.∊ stones
q0414 ← 3⊃(nums[⍒nums] ∪nums), ⌈/nums
q0053 ← ⌈/∊∘.-⍨0,+\nums
q0058 ← ≢⊃¯1↑⊆⍨' '≠s
q0228 ← {∪¨,⌿1 ¯1∘.↑⍵⊆⍨⍳⍨⍵-⍳≢⍵}
@adam-nathan
adam-nathan / common-utils.fsx
Created May 20, 2021 08:09
F# common utils
let todo<'a> : 'a = Unchecked.defaultof<'a>
let print x = printfn $"{x}"
@adam-nathan
adam-nathan / call-by-name.fsx
Created May 10, 2021 12:05
Call-by-name semantics in F#
open System
let rnd = Random()
let randint<'a> =
print "generating random number"
rnd.Next(0,10)
type Signal = Signal with
member __.Return x = x
member __.Delay (f:unit -> _) = f
@adam-nathan
adam-nathan / signal.scala
Created May 3, 2021 07:25
Reactive programming in Scala (taken from Functional Program Design in Scala week 4 @ Coursera)
import scala.util.DynamicVariable
class Signal[T](expr: => T) {
import Signal._
private var myExpr: () => T = _
private var myValue: T = _
private var observers: Set[Signal[_]] = Set()
private var observed: List[Signal[_]] = Nil
update(expr)