Skip to content

Instantly share code, notes, and snippets.

@kroger
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kroger/1ad4d711bd07a06bf222 to your computer and use it in GitHub Desktop.
Save kroger/1ad4d711bd07a06bf222 to your computer and use it in GitHub Desktop.
def p():
return p()
def test(x, y):
return 0 if x == 0 else y
test(0, p())
from operator import add, sub
def a_plus_abs_b(a, b):
return (add if b > 0 else sub)(a, b)
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
# applicative order normal order
f(5) f(5)
sum_of_squares(5+1, 5*2) sum_of_squares(5+1, 5*2)
sum_of_squares(6, 10) square(5+1) + square(5*2)
square(6) + square(10) ((5+1) * (5+1)) + ((5*2) * (5*2))
(6 * 6) + (10 * 10) (6 * 6) + (10 * 10)
36 + 100 36 + 100
136 136
def average(x, y):
return (x + y)/2
def sqrt(x):
def is_good_enough(guess, x):
return abs(square(guess) - x) < 0.001
def improve(guess, x):
return average(guess, x/guess)
def sqrt_iter(guess, x):
if is_good_enough(guess, x):
return guess
else:
return sqrt_iter(improve(guess, x), x)
return sqrt_iter(1.0, x)
>>> import dis
>>> dis.dis(square)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 RETURN_VALUE
>>> dis.dis(square2)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 RETURN_VALUE
def is_good_enough(guess, x):
return abs(square(guess) - x) < 0.001
def improve(guess, x):
return average(guess, x/guess)
square2 = lambda x: x * x
lambda x: x * x
def sqrt(x):
def is_good_enough(guess):
return abs(square(guess) - x) < 0.001
def improve(guess):
return average(guess, x/guess)
def sqrt_iter(guess):
if is_good_enough(guess):
return guess
else:
return sqrt_iter(improve(guess))
return sqrt_iter(1.0)
def myabs(x):
if x > 0:
return x
elif x == 0:
return x
elif x < 0:
return x
def myabs(x):
if x < 0:
return -x
else:
return x
def myabs(x):
return -x if x < 0 else x
def sqrt(x):
return sqrt_iter(1.0, x)
def sqrt_iter(guess, x):
if is_good_enough(guess, x):
return guess
else:
return sqrt_iter(improve(guess, x), x)
square(2 + 5)
square(square(7 + square (3)))
def square(x):
return x * x
def sum_of_squares(x, y):
return square(x) + square(y)
sum_of_squares(3, 4)
def f(a):
return sum_of_squares(a + 1, a * 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment