Last active
May 12, 2017 13:04
-
-
Save pembeci/16bcbd8c73549c9af6a3e4e3f2bdf7d0 to your computer and use it in GitHub Desktop.
CENG 2002 PL Concepts - Functional Programming - Lecture 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, ... | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment