Skip to content

Instantly share code, notes, and snippets.

@pembeci
Last active May 12, 2017 13:04
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 pembeci/16bcbd8c73549c9af6a3e4e3f2bdf7d0 to your computer and use it in GitHub Desktop.
Save pembeci/16bcbd8c73549c9af6a3e4e3f2bdf7d0 to your computer and use it in GitHub Desktop.
CENG 2002 PL Concepts - Functional Programming - Lecture 1
b = 8
def do_something(a):
global b
b += 1
return a + b
print(do_something(40))
print("b is now", b)
print(do_something(40))
print(do_something(40))
import time
def make_counter():
print("IN make_counter")
cnt = 0
time.sleep(2)
def count():
nonlocal cnt
print("IN count")
cnt += 1
print("COUNT=", cnt)
print("RETURNING FROM make_counter")
return count
c1 = make_counter()
c2 = make_counter()
c3 = make_counter()
c1()
c1()
c1()
c2()
c3()
c2()
c1()
def make_counter2(start_val=0, incr=1):
cnt = start_val
def count():
message = "COUNT="
nonlocal cnt
print("IN count")
cnt += incr
print(message, cnt)
message = "NEW MESG="
return count
c4 = make_counter2() # 1, 2, 3, 4, ...
c5 = make_counter2(100,5) # 105, 110, 115, 120, ...
c6 = make_counter2(20) # 21, 22, 23, 24, ...
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# fib = memoize(fib)
# print(fib(40))
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment