Skip to content

Instantly share code, notes, and snippets.

View zachallaun's full-sized avatar

Zach Allaun zachallaun

View GitHub Profile
import re
import collections
Failure = collections.namedtuple("Failure", ["unparsed"])
def failure(unparsed=None):
return Failure(unparsed)
def isfailure(val):
return isinstance(val, Failure)

#| #| #| #| #|

Building List Comprehensions from Scratch

#| #|

(defmacro list-comp (bindings body)
(cond
((= 0 (length bindings))
`(list ,body))
((eq :when (caar bindings))
`(if ,(cadar bindings)
(list-comp ,(cdr bindings) ,body)))
(t `(apply #'append (mapcar (lambda (,(caar bindings))
(list-comp ,(cdr bindings) ,body))
,(cadar bindings))))))
NUMS = ['10', '9', '8', '7', '6', '5', '4', '3', '2', '1']
OPS = ['', '+', '-', '*', '/']
def interpositions(seq, divs):
if len(seq) == 1:
return [seq]
return ([seq[0], div] + interposed for interposed in interpositions(seq[1:], divs)
for div in divs)
print([''.join(interposed) for interposed in interpositions(NUMS, OPS) if eval(''.join(interposed)) == 2013])
julia> function transform(ex)
:(println("transformed"); $(esc(ex)))
end
# methods for generic function transform
transform(ex) at none:2
julia> macro t(ex)
transform(ex)
end
# Using @async
immutable Continuation
args
end
cont(args...) = Continuation(args)
immutable Actor
ref::RemoteRef
mailbox::RemoteRef

#| #| #| #| #|

Building List Comprehensions from Scratch

... now with syntax!!!

#|

# time
# ====
macro time(ex)
quote
local t0 = time_ns()
local val = $(esc(ex))
local t1 = time_ns()
println("elapsed time: ", (t1-t0)/1e9, " seconds")
val
@zachallaun
zachallaun / gist:5447466
Last active December 16, 2015 14:19
Pattern matching on Julia syntax
remove_quote_block(val) = val
remove_quote_block(ex::Expr) =
ex.head == :block && length(ex.args) == 2 ? ex.args[2] : ex
remove_quote_block(exs...) = map(remove_quote_block, exs)
function syntax_bindings(ex, template::Symbol, collected::Dict)
s = string(template)
if s[1] == '_' && s[end] == '_'
collected[template] = ex
@zachallaun
zachallaun / unify.jl
Last active December 17, 2015 10:28
Some simple unification in Julia… on its way to simple pattern matching.
module Unify
using FunctionalCollections
export unify, extended, lvar, Anything
const _LogicVarKey = 0x1f75f6e80ac3828f
immutable LogicVar
name