├── 2005 ├── .DS_Store ├── hw1 │ ├── hw1.pdf │ ├── johnson_hw1.sml │ └── johnson_hw1_test.sml ├── hw2 │ ├── hw2.pdf │ ├── johnson_hw2.sml │ └── johnson_hw2_test.sml ├── hw3 │ ├── hw3-provided.sml │ ├── hw3.pdf │ ├── johnson_hw3.sml │ └── johnson_hw3_test.sml ├── hw4 │ └── hw4.pdf ├── hw5 │ ├── hw5.pdf │ ├── hw5provided.scm │ ├── hw5test.txt │ ├── hw5test_output.txt │ ├── minischemev2.scm │ └── minischemev_2.scm └── hw6 │ └── hw6.pdf ├── 2013 ├── .DS_Store ├── hw1 │ ├── .DS_Store │ ├── hw1.pdf │ ├── johnson_hw1.sml │ ├── johnson_hw1.sml~ │ ├── johnson_hw1_test.sml │ ├── johnson_hw1_test.sml~ │ └── unit1notes.pdf ├── hw2 │ ├── hw2.pdf │ ├── hw2provided.sml │ ├── hw2provided.sml~ │ ├── hw2providedTests.sml │ ├── johnson_hw2.sml │ ├── johnson_hw2.sml~ │ ├── johnson_hw2_test.sml │ ├── johnson_hw2_test.sml~ │ └── unit2notes.pdf ├── hw3 │ ├── #johnson_hw3.sml# │ ├── .#johnson_hw3.sml │ ├── hw3.pdf │ ├── hw3provided.sml │ ├── johnson_hw3.sml │ ├── johnson_hw3.sml~ │ ├── johnson_hw3_test.sml │ ├── johnson_hw3_test.sml~ │ └── unit3notes.pdf ├── hw4 │ ├── curry.jpg │ ├── dan.jpg │ ├── dog.jpg │ ├── dog2.jpg │ ├── hw4.pdf │ ├── hw4.rkt.txt │ └── hw4tests.rkt.txt ├── hw5 │ ├── hw5.pdf │ ├── hw5.rkt.txt │ └── hw5tests.rkt.txt ├── hw6 │ ├── hw6.pdf │ ├── hw6assignment.rb │ ├── hw6graphics.rb │ ├── hw6provided.rb │ └── hw6runner.rb └── hw7 │ ├── .DS_Store │ ├── hw7.pdf │ ├── hw7.rb │ ├── hw7.sml │ ├── hw7testsprovided.rb │ └── hw7testsprovided.sml ├── 1997_Autumn ├── .DS_Store └── minor assignment │ ├── johnson.sml │ └── johnson.sml~ ├── 2001_spring ├── hw3 │ ├── hw3.pdf │ ├── johnson_hw3.sml │ ├── johnson_hw3.sml~ │ ├── johnson_hw3_test.sml │ └── johnson_hw3_test.sml~ └── hw4 │ ├── hw4.pdf │ ├── johnson_hw4.sml │ └── johnson_hw4.sml~ ├── 2003_autumn └── assignment 5 │ ├── CSE 341 Assignment 5 (Autumn 2003).pdf │ ├── johnson_hw5.sml │ ├── johnson_hw5.sml~ │ ├── johnson_hw5_test.sml │ └── johnson_hw5_test.sml~ ├── 2003_spring └── assignment 5 │ ├── CSE 341 Assignment 5 (Spring 2003).pdf │ ├── johnson_hw5.sml │ └── johnson_hw5.sml~ ├── 2005_autumn ├── hw1 │ ├── hw1.pdf │ └── johnson_hw1.sml └── hw2 │ ├── hw2.pdf │ └── johnson_hw2.sml ├── 2005_spring ├── hw1 │ ├── hw1.pdf │ └── johnson_hw1.sml ├── hw2 │ ├── hw2.pdf │ └── johnson_hw2.sml └── hw3 │ ├── #johnson_hw3.sml# │ ├── .#johnson_hw3.sml │ ├── hw3.pdf │ ├── johnson_hw3.sml │ └── johnson_hw3.sml~ ├── 2006_spring ├── hw1 │ ├── hw1.pdf │ ├── johnson_hw1.sml │ └── johnson_hw1_tests.sml └── hw2 │ ├── hw2.pdf │ ├── johnson_hw2.sml │ └── johnson_hw2.sml~ ├── 2006_winter ├── hw1 │ ├── basra_part1.pdf │ └── johnson_hw1.sml ├── hw2 │ ├── basra_full.sml │ ├── basra_part2.pdf │ ├── basra_work.sml │ └── johnson_hw2.sml └── hw3 │ ├── .#johnson_hw3.sml │ ├── hw3.pdf │ ├── johnson_hw3.sml │ └── johnson_hw3.sml~ ├── 2007_spring ├── hw1 │ ├── FAQ - The Rules To the Game of Othello.pdf │ ├── hw1.pdf │ ├── othello-tests.sml │ └── othello.sml └── hw2 │ ├── hw2.pdf │ ├── hw2.sml │ └── hw2.sml~ ├── 2007_winter └── hw1 │ ├── .#johnson_hw1.sml │ ├── CSE341, Winter 2007.pdf │ └── johnson_hw1.sml ├── ML-Book.pdf ├── courses.cs.washington.edu:courses:cse341:13sp.pdf ├── hw1 ├── hw1.pdf ├── johnson_hw1.sml └── johnson_hw1_test.sml ├── hw2 ├── hw2.pdf ├── hw2provided.sml ├── hw2provided.sml~ ├── hw2providedTests.sml ├── johnson_hw2.sml ├── johnson_hw2.sml~ ├── johnson_hw2_test.sml └── johnson_hw2_test.sml~ ├── hw3 ├── hw3.pdf ├── hw3provided.sml ├── johnson_hw3.sml ├── johnson_hw3_test.sml └── unit3notes.pdf ├── test.sml └── unit1notes.pdf /1997_Autumn/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/1997_Autumn/.DS_Store -------------------------------------------------------------------------------- /1997_Autumn/minor assignment/johnson.sml: -------------------------------------------------------------------------------- 1 | (* 2 | Compute the length of a list (without using the built in length function.) 3 | Cycle a list once. That is, given the list [1, 2, 3, 4, 5], produce the output [2, 3, 4, 5, 1]. 4 | Cycle a list the other way. That is, given the list [1, 2, 3, 4, 5], produce the output [5, 1, 2, 3, 4]. 5 | Remove all of the odd numbers from a list of integers. 6 | Remove all of the vowels from a string. 7 | *) 8 | fun compute_length [] = 0 9 | | compute_length (_::xs') = 1 + compute_length xs' 10 | 11 | fun cyclel (x::xs') = xs'@[x] 12 | | cyclel [] = [] 13 | 14 | fun cycler l = 15 | let fun helper l acc = 16 | case l of 17 | [] => [] 18 | | x::[] => x::acc 19 | | x::xs' => helper xs' (acc@[x]) 20 | in helper l [] 21 | end 22 | 23 | fun remove_odds [] = [] 24 | | remove_odds (x::xs') = case (x mod 2 = 0) of 25 | true => x::(remove_odds xs') 26 | | false => remove_odds xs' 27 | 28 | val remove_odds2 = List.foldl (fn(x,acc)=>if (x mod 2) = 0 then acc@[x] else acc) [] 29 | 30 | fun remove_vowels l = String.implode(List.foldl (fn(x, acc)=> 31 | if not (x = #"a" orelse 32 | x = #"e" orelse 33 | x = #"i" orelse 34 | x = #"o" orelse 35 | x = #"u" orelse 36 | x = #"A" orelse 37 | x = #"E" orelse 38 | x = #"I" orelse 39 | x = #"O" orelse 40 | x = #"U" 41 | ) 42 | then acc@[x] 43 | else acc) 44 | [] 45 | (String.explode(l))); 46 | 47 | 48 | -------------------------------------------------------------------------------- /1997_Autumn/minor assignment/johnson.sml~: -------------------------------------------------------------------------------- 1 | Standard ML of New Jersey v110.77 [built: Fri Apr 17 22:39:11 2015] 2 | - -------------------------------------------------------------------------------- /2001_spring/hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2001_spring/hw3/hw3.pdf -------------------------------------------------------------------------------- /2001_spring/hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | type (''k,'v) assoc_list = (''k * 'v) list 2 | type Records = {losses:int, wins:int} 3 | 4 | exception NotFound 5 | exception NotInLeague 6 | exception WinnerLoserSame 7 | val empty_assoc_list: (''k,'v) assoc_list = [] 8 | val init_rec = {losses= 0, wins=0} 9 | 10 | fun store ([],k,v) = [(k,v)] 11 | | store ((x as (k1,_))::xs',k,v) = if k1 = k then (k,v)::xs' else x::store(xs',k,v) 12 | 13 | fun fetch ([],k) = raise NotFound 14 | | fetch ((k1,v)::xs',k) = if k1 = k then v else fetch(xs',k) 15 | 16 | fun create_league ([]) = [] 17 | | create_league (x::xs') = store((create_league xs'), x, init_rec) 18 | 19 | fun record_game ([], _) = raise NotInLeague 20 | | record_game (ls, {loser,winner}) = 21 | let 22 | val {losses=ll,wins=lw} = fetch(ls, loser) handle NotFound => raise NotInLeague 23 | val update_loser = store (ls,loser, {losses=ll+1,wins=lw}) 24 | val {losses=wl,wins=ww} = fetch(update_loser, winner) handle NotFound => raise NotInLeague 25 | val updated_list as update_winner = store (update_loser, winner, {losses=wl,wins=ww+1}) 26 | in updated_list 27 | end 28 | 29 | fun better_record ({losses=l1,wins=w1},{losses=l2,wins=w2}) = (w1-l1)>(w2-l2) 30 | fun sort_standings [] = [] 31 | | sort_standings ((r as (_,x as pivot))::xs') = 32 | sort_standings((List.foldl (fn(e,acc)=> if better_record(x,#2 e) then acc@[e] else acc) [] xs'))@ 33 | (List.foldl (fn(e,acc)=> if (not (better_record(x,#2 e))) andalso 34 | (not (better_record(#2 e,x))) 35 | then acc@[e] 36 | else acc) 37 | [r] 38 | xs')@ 39 | sort_standings((List.foldl (fn(e,acc)=> if better_record(#2 e,x) then acc@[e] else acc) [] xs')) 40 | 41 | 42 | fun print_league l = 43 | List.foldl (fn( (n,{losses=l,wins=w}),acc)=> 44 | (print ("\n" ^ Int.toString(acc) ^ ") "^n^" Losses: "^(Int.toString(l))^" | Wins: "^(Int.toString(w))); acc + 1)) 45 | 1 46 | (sort_standings l) 47 | 48 | -------------------------------------------------------------------------------- /2001_spring/hw3/johnson_hw3.sml~: -------------------------------------------------------------------------------- 1 | 2 | type (''k,'v) assoc_list = (''k * 'v) list 3 | -------------------------------------------------------------------------------- /2001_spring/hw3/johnson_hw3_test.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw3.sml"; 2 | val name_hw = "2001 - Homework 3 - Association Lists" 3 | 4 | val f1=store 5 | val f2=fetch 6 | val f3=create_league 7 | val f4=record_game 8 | val f5=better_record 9 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 10 | 11 | val nba_leagues = [ 12 | "Atlanta Hawks", 13 | "Boston Celtics", 14 | "Charlotte Bobcats", 15 | "Chicago Bulls", 16 | "Cleveland Cavaliers", 17 | "Dallas Mavericks", 18 | "Denver Nuggets", 19 | "Detroit Pistons", 20 | "Golden State Warriors", 21 | "Houston Rockets", 22 | "Indiana Pacers", 23 | "LA Clippers", 24 | "LA Lakers", 25 | "Memphis Grizzlies", 26 | "Miami Heat", 27 | "Milwaukee Bucks", 28 | "Minnesota Timberwolves", 29 | "New Jersey Nets", 30 | "New Orleans Hornets", 31 | "New York Knicks", 32 | "Oklahoma City Thunder", 33 | "Orlando Magic", 34 | "Philadelphia Sixers", 35 | "Phoenix Suns", 36 | "Portland Trail Blazers", 37 | "Sacramento Kings", 38 | "San Antonio Spurs", 39 | "Toronto Raptors", 40 | "Utah Jazz", 41 | "Washington Wizards" 42 | ] 43 | val control = [ 44 | ("Washington Wizards",{losses=0,wins=0}), 45 | ("Utah Jazz",{losses=0,wins=0}), 46 | ("Toronto Raptors",{losses=0,wins=0}), 47 | ("San Antonio Spurs",{losses=0,wins=0}), 48 | ("Sacramento Kings",{losses=0,wins=0}), 49 | ("Portland Trail Blazers",{losses=0,wins=0}), 50 | ("Phoenix Suns",{losses=0,wins=0}), 51 | ("Philadelphia Sixers",{losses=0,wins=0}), 52 | ("Orlando Magic",{losses=0,wins=0}), 53 | ("Oklahoma City Thunder",{losses=0,wins=0}), 54 | ("New York Knicks",{losses=0,wins=0}), 55 | ("New Orleans Hornets",{losses=0,wins=0}), 56 | ("New Jersey Nets",{losses=0,wins=0}), 57 | ("Minnesota Timberwolves",{losses=0,wins=0}), 58 | ("Milwaukee Bucks",{losses=0,wins=0}), 59 | ("Miami Heat",{losses=0,wins=0}), 60 | ("Memphis Grizzlies",{losses=0,wins=0}), 61 | ("LA Lakers",{losses=0,wins=0}), 62 | ("LA Clippers",{losses=0,wins=0}), 63 | ("Indiana Pacers",{losses=0,wins=0}), 64 | ("Houston Rockets",{losses=0,wins=0}), 65 | ("Golden State Warriors",{losses=0,wins=0}), 66 | ("Detroit Pistons",{losses=0,wins=0}), 67 | ("Denver Nuggets",{losses=0,wins=0}), 68 | ("Dallas Mavericks",{losses=0,wins=0}), 69 | ("Cleveland Cavaliers",{losses=0,wins=0}), 70 | ("Chicago Bulls",{losses=0,wins=0}), 71 | ("Charlotte Bobcats",{losses=0,wins=0}), 72 | ("Boston Celtics",{losses=0,wins=0}), 73 | ("Atlanta Hawks",{losses=0,wins=0}) 74 | ] 75 | 76 | val tests = [ 77 | ("1.00", f1([],"","") = [("","")]), 78 | ("1.01", f1([],"1","test") = [("1","test")]), 79 | ("1.02", f1([("0","init")],"1","test") = [("0","init"),("1","test")]), 80 | ("1.03", f1([("0","init"),("1","input")],"1","test") = [("0","init"),("1","test")]), 81 | ("1.04", f1([("0","init"),("1","input"),("2","input")],"1","test") = [("0","init"),("1","test"),("2","input")]), 82 | ("1.05", f1([("0","init"),("1","input"),("2","input")],"2","test") = [("0","init"),("1","input"),("2","test")]), 83 | ("1.06", f1([("0","init"),("1","input"),("2","input")],"0","test") = [("0","test"),("1","input"),("2","input")]), 84 | 85 | ("2.00", f2([],"") = "nonsense" handle NotFound => true), 86 | ("2.00", f2([("1","nonsense")],"") = "nonsense" handle NotFound => true), 87 | ("2.00", f2([("1","nonsense")],"1") = "nonsense"), 88 | ("2.00", f2([("1","nonsense"),("2","input")],"1") = "nonsense"), 89 | ("2.00", f2([("1","nonsense"),("2","input")],"2") = "input"), 90 | ("2.00", f2([("1","nonsense"),("2","input"),("3","init")],"0") = "nonsense" handle NotFound => true), 91 | ("2.00", f2([("1","nonsense"),("2","input"),("3","init")],"4") = "nonsense" handle NotFound => true), 92 | ("2.00", f2([("1","nonsense"),("2","input"),("3","init")],"1") = "nonsense"), 93 | ("2.00", f2([("1","nonsense"),("2","input"),("3","init")],"2") = "input"), 94 | ("2.00", f2([("1","nonsense"),("2","input"),("3","init")],"3") = "init"), 95 | 96 | ("3.00", f3 [] = []), 97 | ("3.01", f3 [""] = [("",{losses= 0, wins=0})]), 98 | ("3.02", f3 nba_leagues = control), 99 | 100 | ("4.00", f4 ([], {loser="",winner=""}) <> [] handle NotInLeague => true), 101 | ("4.01", f4 (f3 ["invalid"], {loser="",winner=""}) <> [] handle NotInLeague => true), 102 | ("4.02", f4 (f3 ["a","b","c"], {loser="",winner=""}) <> [] handle NotInLeague => true), 103 | ("4.03", f4 (f3 ["a","b","c"], {loser="a",winner=""}) <> [] handle NotInLeague => true), 104 | ("4.04", f4 (f3 ["a","b","c"], {loser="",winner="b"}) <> [] handle NotInLeague => true), 105 | ("4.05", f4 (f3 ["a","b","c"], {loser="c",winner=""}) <> [] handle NotInLeague => true), 106 | 107 | ("4.10", f4 (f3 [""], {loser="",winner=""}) = [("",{losses=1,wins=1})]), 108 | ("4.11", f4 (f3 ["1",""], {loser="1",winner=""}) = [("",{losses=0,wins=1}),("1",{losses=1,wins=0})]), 109 | ("4.12", f4 (f3 ["2","1",""], {loser="1",winner=""}) = [("",{losses=0,wins=1}),("1",{losses=1,wins=0}),("2",{losses=0,wins=0})]), 110 | 111 | ("5.00", f5 ({losses=0,wins=0},{losses=0,wins=0}) = false), 112 | ("5.01", f5 ({losses=1,wins=0},{losses=0,wins=0}) = false), 113 | ("5.02", f5 ({losses=0,wins=1},{losses=0,wins=0}) = true), 114 | ("5.03", f5 ({losses=0,wins=0},{losses=1,wins=0}) = true), 115 | ("5.04", f5 ({losses=0,wins=0},{losses=0,wins=1}) = false), 116 | ("5.05", f5 ({losses=3,wins=10},{losses=20,wins=3})=true), 117 | ("5.06", f5 ({losses=3,wins=10},{losses=20,wins=30})=false) 118 | 119 | ]; 120 | 121 | print ("\n----------------------"^name_hw^"--------------------------\n"); (*Name display to assert correct test file is running*) 122 | fun all_tests(tests) = 123 | let fun helper(tests: (string*bool) list, all_passed) = 124 | case tests of 125 | [] => all_passed 126 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 127 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 128 | in 129 | helper(tests, true) 130 | end; 131 | 132 | case all_tests(tests) of 133 | true => print "--------------EVERY TESTS PASSED-------------\n" 134 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 135 | -------------------------------------------------------------------------------- /2001_spring/hw3/johnson_hw3_test.sml~: -------------------------------------------------------------------------------- 1 | use "johnson_hw3.sml"; 2 | -------------------------------------------------------------------------------- /2001_spring/hw4/hw4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2001_spring/hw4/hw4.pdf -------------------------------------------------------------------------------- /2001_spring/hw4/johnson_hw4.sml: -------------------------------------------------------------------------------- 1 | fun alist_map (f, al) = List.map f al 2 | fun team_names al = alist_map ((fn(k, v) => k), al) 3 | 4 | fun alist_reduce (f, b, nil) = b 5 | | alist_reduce (f, b, (k,v)::rest) = f(k, v, alist_reduce (f, b, rest)) 6 | fun better_record ({losses=l1,wins=w1}, {losses=l2,wins=w2}) = w1-l1 > w2-l2 7 | fun best_record l = alist_reduce ((fn(k,v,rest)=> if better_record(v,rest) then v else rest), {losses=0,wins=0}, l) 8 | 9 | fun all_games_back l = 10 | let val no1 as {losses=l1,wins=w1} = best_record l 11 | in alist_map ((fn(k, {losses=l2,wins=w2})=> (k,real((l2-l1)-(w2-w1))/2.0)), l) 12 | end 13 | 14 | val nba_leagues = [ 15 | "Atlanta Hawks", 16 | "Boston Celtics", 17 | "Charlotte Bobcats", 18 | "Chicago Bulls", 19 | "Cleveland Cavaliers", 20 | "Dallas Mavericks", 21 | "Denver Nuggets", 22 | "Detroit Pistons", 23 | "Golden State Warriors", 24 | "Houston Rockets", 25 | "Indiana Pacers", 26 | "LA Clippers", 27 | "LA Lakers", 28 | "Memphis Grizzlies", 29 | "Miami Heat", 30 | "Milwaukee Bucks", 31 | "Minnesota Timberwolves", 32 | "New Jersey Nets", 33 | "New Orleans Hornets", 34 | "New York Knicks", 35 | "Oklahoma City Thunder", 36 | "Orlando Magic", 37 | "Philadelphia Sixers", 38 | "Phoenix Suns", 39 | "Portland Trail Blazers", 40 | "Sacramento Kings", 41 | "San Antonio Spurs", 42 | "Toronto Raptors", 43 | "Utah Jazz", 44 | "Washington Wizards" 45 | ] 46 | val control = [ 47 | ("Washington Wizards",{losses=0,wins=0}), 48 | ("Utah Jazz",{losses=0,wins=10}), 49 | ("Toronto Raptors",{losses=5,wins=10}), 50 | ("San Antonio Spurs",{losses=30,wins=50}), 51 | ("Sacramento Kings",{losses=10,wins=70}), 52 | ("Portland Trail Blazers",{losses=10,wins=90}), 53 | ("Phoenix Suns",{losses=100,wins=60}), 54 | ("Philadelphia Sixers",{losses=90,wins=20}), 55 | ("Orlando Magic",{losses=70,wins=10}), 56 | ("Oklahoma City Thunder",{losses=60,wins=2}), 57 | ("New York Knicks",{losses=0,wins=4}), 58 | ("New Orleans Hornets",{losses=40,wins=6}), 59 | ("New Jersey Nets",{losses=30,wins=7}), 60 | ("Minnesota Timberwolves",{losses=0,wins=100}), 61 | ("Milwaukee Bucks",{losses=50,wins=110}), 62 | ("Miami Heat",{losses=10,wins=120}), 63 | ("Memphis Grizzlies",{losses=0,wins=130}), 64 | ("LA Lakers",{losses=120,wins=150}), 65 | ("LA Clippers",{losses=110,wins=90}), 66 | ("Indiana Pacers",{losses=100,wins=80}), 67 | ("Houston Rockets",{losses=90,wins=70}), 68 | ("Golden State Warriors",{losses=80,wins=60}), 69 | ("Detroit Pistons",{losses=70,wins=50}), 70 | ("Denver Nuggets",{losses=60,wins=40}), 71 | ("Dallas Mavericks",{losses=50,wins=30}), 72 | ("Cleveland Cavaliers",{losses=40,wins=20}), 73 | ("Chicago Bulls",{losses=30,wins=10}), 74 | ("Charlotte Bobcats",{losses=20,wins=30}), 75 | ("Boston Celtics",{losses=20,wins=90}), 76 | ("Atlanta Hawks",{losses=10,wins=45}) 77 | ] 78 | 79 | all_games_back control 80 | -------------------------------------------------------------------------------- /2001_spring/hw4/johnson_hw4.sml~: -------------------------------------------------------------------------------- 1 | fun alist_map (f, al) = List.map f al 2 | fun team_names al = alist_map(fn( (k, v) => k), al) 3 | 4 | fun alist_reduce (f, b, nil) = b 5 | | alist_reduce (f, b, (k,v)::rest) = f(k, v, alist_reduce (f, b, rest)) 6 | fun better_record ({losses=l1,wins=w1}, {losses=l2,wins=w2}) = w1-l1 > w2-l2 7 | fun best_record l = alist_reduce ((fn(k,v,rest)=> if better_record(v,rest) then v else rest), {losses=0,wins=0}, l) 8 | 9 | fun all_games_back l = 10 | let val no1 as {losses=l1,wins=w1} = best_record l 11 | in alist_map ((fn(k, {losses=l2,wins=w2})=> (k,real((l2-l1)-(w2-w1))/2.0)), l) 12 | end 13 | 14 | val nba_leagues = [ 15 | "Atlanta Hawks", 16 | "Boston Celtics", 17 | "Charlotte Bobcats", 18 | "Chicago Bulls", 19 | "Cleveland Cavaliers", 20 | "Dallas Mavericks", 21 | "Denver Nuggets", 22 | "Detroit Pistons", 23 | "Golden State Warriors", 24 | "Houston Rockets", 25 | "Indiana Pacers", 26 | "LA Clippers", 27 | "LA Lakers", 28 | "Memphis Grizzlies", 29 | "Miami Heat", 30 | "Milwaukee Bucks", 31 | "Minnesota Timberwolves", 32 | "New Jersey Nets", 33 | "New Orleans Hornets", 34 | "New York Knicks", 35 | "Oklahoma City Thunder", 36 | "Orlando Magic", 37 | "Philadelphia Sixers", 38 | "Phoenix Suns", 39 | "Portland Trail Blazers", 40 | "Sacramento Kings", 41 | "San Antonio Spurs", 42 | "Toronto Raptors", 43 | "Utah Jazz", 44 | "Washington Wizards" 45 | ] 46 | val control = [ 47 | ("Washington Wizards",{losses=0,wins=0}), 48 | ("Utah Jazz",{losses=0,wins=0}), 49 | ("Toronto Raptors",{losses=0,wins=0}), 50 | ("San Antonio Spurs",{losses=0,wins=0}), 51 | ("Sacramento Kings",{losses=0,wins=0}), 52 | ("Portland Trail Blazers",{losses=0,wins=0}), 53 | ("Phoenix Suns",{losses=0,wins=0}), 54 | ("Philadelphia Sixers",{losses=0,wins=0}), 55 | ("Orlando Magic",{losses=0,wins=0}), 56 | ("Oklahoma City Thunder",{losses=0,wins=0}), 57 | ("New York Knicks",{losses=0,wins=0}), 58 | ("New Orleans Hornets",{losses=0,wins=0}), 59 | ("New Jersey Nets",{losses=0,wins=0}), 60 | ("Minnesota Timberwolves",{losses=0,wins=0}), 61 | ("Milwaukee Bucks",{losses=0,wins=0}), 62 | ("Miami Heat",{losses=0,wins=0}), 63 | ("Memphis Grizzlies",{losses=0,wins=0}), 64 | ("LA Lakers",{losses=0,wins=0}), 65 | ("LA Clippers",{losses=0,wins=0}), 66 | ("Indiana Pacers",{losses=0,wins=0}), 67 | ("Houston Rockets",{losses=0,wins=0}), 68 | ("Golden State Warriors",{losses=0,wins=0}), 69 | ("Detroit Pistons",{losses=0,wins=0}), 70 | ("Denver Nuggets",{losses=0,wins=0}), 71 | ("Dallas Mavericks",{losses=0,wins=0}), 72 | ("Cleveland Cavaliers",{losses=0,wins=0}), 73 | ("Chicago Bulls",{losses=0,wins=0}), 74 | ("Charlotte Bobcats",{losses=0,wins=0}), 75 | ("Boston Celtics",{losses=0,wins=0}), 76 | ("Atlanta Hawks",{losses=0,wins=0}) 77 | ] 78 | 79 | -------------------------------------------------------------------------------- /2003_autumn/assignment 5/CSE 341 Assignment 5 (Autumn 2003).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2003_autumn/assignment 5/CSE 341 Assignment 5 (Autumn 2003).pdf -------------------------------------------------------------------------------- /2003_autumn/assignment 5/johnson_hw5.sml: -------------------------------------------------------------------------------- 1 | (*Compiler.Control.Print.printDepth := 1000; 2 | Compiler.Control.Print.printLength := 1000; 3 | Compiler.Control.Print.stringDepth := 1000; 4 | SMLofNJ.Internals.GC.messages false; 5 | *) 6 | exception InsufficientArguments 7 | exception NothingApplies 8 | 9 | fun next l = 10 | let val convert_to_real = List.map (fn(x)=>real(x)) 11 | val split = List.foldl (fn(e,(evens,unevens,i)) => if (i mod 2) = 0 12 | then (evens@[e],unevens,i+1) 13 | else (evens,unevens@[e],i+1)) 14 | ([],[],0) 15 | fun coupling l = ListPair.zip (#1 (split l), #2 (split l)) 16 | fun couple_repeat (first::xs') = 17 | let val last::xs'' = List.rev xs' 18 | val l = List.rev xs'' 19 | in coupling (first::(List.foldl (fn(e,acc)=> acc@[e,e]) [] l)@[last]) 20 | end 21 | fun round factor = 22 | let val sign = if factor < 0.0 then ~1.0 else 1.0 23 | val fact = factor * sign 24 | in if fact > 0.0 andalso fact < 10.0 then ceil(100000.0 * factor) 25 | else if fact > 10.0 andalso fact < 100.0 then ceil(10000.0 * factor) 26 | else if fact > 100.0 andalso fact < 1000.0 then ceil(1000.0 * factor) 27 | else ceil(100.0 * factor) 28 | end 29 | fun check_pattern f ((x as (_,last))::[]) = SOME (last, f x) 30 | | check_pattern f (e::cl') = if (List.all (fn(x)=>round(f(x))=round(f(e)) 31 | handle _ => false) 32 | cl') 33 | then check_pattern f [List.last cl'] 34 | else NONE 35 | fun arithmetic l = case (check_pattern (fn(x,y)=>y-x) l) of 36 | NONE => NONE 37 | | SOME (last, surplus) => SOME (last + surplus) 38 | fun geometric l = case (check_pattern (fn(x,y)=>y/x) l) of 39 | NONE => NONE 40 | | SOME (last, factor) => SOME (last * factor) 41 | fun interleaved (e1::e2::[]) = NONE 42 | | interleaved (e1::e2::e3::[]) = NONE 43 | | interleaved l = 44 | let val evens = couple_repeat(#1 (split l)) 45 | val unevens = couple_repeat(#2 (split l)) 46 | val l_has_even = List.length(l) mod 2 = 0 47 | fun retrieve a b = if l_has_even then SOME a else SOME b 48 | in case (arithmetic evens, arithmetic unevens, geometric evens, geometric unevens) of 49 | (SOME ne, SOME nu, _, _)=> retrieve ne nu 50 | | (SOME ne, NONE, _, SOME nu) => retrieve ne nu 51 | | (NONE, SOME nu, SOME ne, _) => retrieve ne nu 52 | | (NONE,NONE,SOME ne, SOME nu) => retrieve ne nu 53 | | (_,_,_,_) => NONE 54 | end 55 | in case (convert_to_real l) of 56 | [] => raise InsufficientArguments 57 | | e::[] => raise InsufficientArguments 58 | | l => case (arithmetic (couple_repeat l), geometric (couple_repeat l), interleaved l) of 59 | (NONE,NONE,NONE) => raise NothingApplies 60 | | (SOME n,_,_) => ceil(n) 61 | | (NONE,SOME n,_) => ceil(n) 62 | | (NONE,NONE,SOME n) => ceil(n) 63 | end 64 | 65 | 66 | fun gen(f, n) = 67 | let fun helper i = 68 | if i = n then [] else f(i)::(helper (i+1)) 69 | in helper 0 70 | end; 71 | 72 | -------------------------------------------------------------------------------- /2003_autumn/assignment 5/johnson_hw5.sml~: -------------------------------------------------------------------------------- 1 | Compiler.Control.Print.printDepth := 1000; 2 | Compiler.Control.Print.printLength := 1000; 3 | Compiler.Control.Print.stringDepth := 1000; 4 | SMLofNJ.Internals.GC.messages false; 5 | -------------------------------------------------------------------------------- /2003_autumn/assignment 5/johnson_hw5_test.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw5.sml"; 2 | val name_hw = "2003 - Autumn - Assignment Five" 3 | 4 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 5 | val tests = [ 6 | ("1.00", (next []) > 0 handle InsufficientArguments => true), 7 | ("1.01", (next [1]) > 1 handle InsufficientArguments => true), 8 | 9 | ("1.10", (next [1,2]) = 3), 10 | ("1.11", (next [1,2,3]) = 4), 11 | ("1.12", (next [1,2,3,4]) = 5), 12 | ("1.13", next [1,3,5] = 7), 13 | ("1.14", next [0,0] = 0), 14 | ("1.15", next [0,0,0] = 0), 15 | ("1.16", next [0,0,0,0] = 0), 16 | ("1.17", next [0,0,0,0,0] = 0), 17 | ("1.18", next [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] = 0), 18 | ("1.19", next [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] = 0), 19 | 20 | ("1.20", (next [1,2,4,8,16,32,64,128,256,512,1024,2048]) = 4096), 21 | ("1.21", (next [1,5,25,125,625]) = 3125), 22 | ("1.22", next [~2, 10, ~50] = 250), 23 | 24 | ("1.30", (next [1,2,4,12]) = 7), 25 | ("1.31", (next [2,2,4,8]) = 6), 26 | ("1.32", (next [0,2,4,8]) = 8), 27 | ("1.33", next [0,10,0,11,0,12,0] = 13), 28 | 29 | ("1.40", (next [1,2,3,4,5,6,7,8,9,10,12]) = ~5 handle NothingApplies => true ), 30 | ("1.41", (next [0,2,3,4,5,6,7,8,9,10,11]) = ~5 handle NothingApplies => true ), 31 | ("1.42", (next [1,2,3,4,5,6,6,7,8,9,10,11]) = ~5 handle NothingApplies => true ), 32 | 33 | ("1.50", (next [1,2,4,5,8]) = ~5 handle NothingApplies => true ), 34 | 35 | ("2.00", gen((fn(n) => 7 + n*2),10) = [7,9,11,13,15,17,19,21,23,25]) 36 | ]; 37 | 38 | print ("\n"^Int.toString(List.length(tests))^" TOTAL TESTS RUN----------------------"^name_hw^"--------------------------\n"); (*Name display to assert correct test file is running*) 39 | fun all_tests(tests) = 40 | let fun helper(tests: (string*bool) list, all_passed) = 41 | case tests of 42 | [] => all_passed 43 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 44 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 45 | in 46 | helper(tests, true) 47 | end; 48 | 49 | case all_tests(tests) of 50 | true => print "--------------EVERY TESTS PASSED-------------\n" 51 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 52 | 53 | 54 | -------------------------------------------------------------------------------- /2003_autumn/assignment 5/johnson_hw5_test.sml~: -------------------------------------------------------------------------------- 1 | use "johnson_hw5.sml"; 2 | 3 | next [] <> [] handle InsufficientArguments => true; 4 | next [1] <> [1] handle InsufficientArguments => true; 5 | next [(1,0)] <> [(1,0)] handle InsufficientArguments => true; 6 | next [[1,0]] <> [[1,0]] handle InsufficientArguments => true; 7 | next [1,2] = 3; 8 | next [1,2,3] = 4; 9 | next [1,2,3,4] = 5; 10 | 11 | -------------------------------------------------------------------------------- /2003_spring/assignment 5/CSE 341 Assignment 5 (Spring 2003).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2003_spring/assignment 5/CSE 341 Assignment 5 (Spring 2003).pdf -------------------------------------------------------------------------------- /2003_spring/assignment 5/johnson_hw5.sml: -------------------------------------------------------------------------------- 1 | (*Polynomial Representation*) 2 | fun polynomial [] = [] 3 | | polynomial (r::[]) = [1.0, ~r] 4 | | polynomial lr = 5 | let fun mult p r = List.foldl (fn((c1,c2),acc) => acc@[c1+c2]) [] (ListPair.zip(p@[0.0], 0.0::(List.map(fn(x) => ~r*x) p))) 6 | fun loop p [] = p 7 | | loop p (r::lr') = loop (mult p r) lr' 8 | val r1::r2::lr'' = lr 9 | in loop (mult [1.0, ~r1] r2) lr'' 10 | end; 11 | 12 | polynomial [~2.0, 2.0]; 13 | polynomial [1.0, 1.0, 1.0]; 14 | polynomial [0.0, 1.0, 2.0, 3.0]; 15 | 16 | (*Rough integrals.*) 17 | fun roughIntegral f a b n = 18 | let val width = (b-a)/n 19 | fun helper c = 20 | if c > b then 0.0 else (f c) + helper (c + width) 21 | in (helper a)*width 22 | end; 23 | 24 | roughIntegral (fn(x)=>Math.sqrt(1.0-x*x)) 0.0 1.0 4.0; 25 | roughIntegral (fn(x)=>Math.sqrt(1.0-x*x)) 0.0 1.0 10.0; 26 | roughIntegral (fn(x)=>x) 10.0 20.0 10.0; 27 | 28 | -------------------------------------------------------------------------------- /2003_spring/assignment 5/johnson_hw5.sml~: -------------------------------------------------------------------------------- 1 | (*Polynomial Representation*) 2 | fun polynomial [] = [] 3 | | polynomial r::[] = [1 ~r] 4 | | polynomial lr = 5 | let fun mult p r = List.foldl (fn((c1,c2),acc)=>acc@[c1+c2]) [] ListPair.zip(p@[0], 0::(List.map(fn(x)=>~r*x) p)) 6 | fun loop p [] = p 7 | | loop p (r::lr') = loop (mult p r) lr' 8 | val r1::r2::lr'' = lr 9 | in loop (mult [1 ~r1] r2) lr'' 10 | end 11 | 12 | 13 | -------------------------------------------------------------------------------- /2005/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/.DS_Store -------------------------------------------------------------------------------- /2005/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw1/hw1.pdf -------------------------------------------------------------------------------- /2005/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | (*Johnson homework1*) 2 | val max = 7 3 | fun legal_bone(s1,s2) = s1 >= 1 andalso s1 <= max andalso s2 >= 1 andalso s2 <= max 4 | fun compatible_bones(b1: int*int,b2: int*int) = (#1 b1) = (#1 b2) orelse (#1 b1) = (#2 b2) orelse (#2 b1) = (#1 b2) orelse (#2 b1) = (#2 b2) 5 | 6 | fun all_legal_bones(blist) = 7 | case blist of 8 | [] => true 9 | | (x::xs') => legal_bone(x) andalso all_legal_bones(xs') 10 | 11 | fun no_doubles(blist) = 12 | case blist of 13 | [] => true 14 | | ((s1,s2)::xs') => s1 <> s2 andalso no_doubles(xs') 15 | 16 | fun make_suit(s) = 17 | let fun helper(n) = 18 | if n >= 1 19 | then if n = s 20 | then (s,n)::helper(n-1) 21 | else (n,s)::(s,n)::helper(n-1) 22 | else [] 23 | in helper(s) 24 | end 25 | 26 | fun all_same_suit(blist) = 27 | let fun helper(s,ls) = 28 | case ls of 29 | [] => true 30 | | (s1,s2)::xs' => (s1 = s orelse s2 = s) andalso helper(s, xs') 31 | in case blist of 32 | [] => false 33 | | x::[] => true 34 | | (s1,s2)::xs' => helper(s1, xs') orelse helper(s2, xs') 35 | end 36 | 37 | fun legal_order(blist) = 38 | let fun helper(ls) = 39 | case ls of 40 | x::[] => true 41 | | (_,s2)::(s1',s2')::xs' => s2 = s1' andalso helper((s1',s2')::xs') 42 | in case blist of 43 | [] => false 44 | | _ => helper(blist) 45 | end 46 | 47 | fun make_line_between(a,b) = 48 | let fun helper(c) = 49 | if c < b 50 | then (c,c+1)::helper(c+1) 51 | else [] 52 | in helper(a) 53 | end 54 | 55 | fun legal_order_r(blist) = 56 | let fun helper(ls) = 57 | case ls of 58 | x::[] => true 59 | | (_,s2)::(s1',s2')::xs' => if s2 = s1' 60 | then helper((s1',s2')::xs') 61 | else s2 = s2' andalso helper((s2',s1')::xs') 62 | in case blist of 63 | [] => false 64 | | x::[] => true 65 | | (s1,s2)::xs' => helper((s1,s2)::xs') orelse helper((s2,s1)::xs') 66 | end 67 | -------------------------------------------------------------------------------- /2005/hw1/johnson_hw1_test.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw1.sml"; 2 | val f1 = legal_bone 3 | val f2 = compatible_bones 4 | val f3 = all_legal_bones 5 | val f4 = no_doubles 6 | val f5 = make_suit 7 | val f6 = all_same_suit 8 | val f7 = legal_order 9 | val f8 = make_line_between 10 | val f9 = legal_order_r 11 | 12 | val tests = [ 13 | 14 | ("1", f1(1,2) andalso f1(1,1) andalso f1(max,max) andalso not (f1(0,2)) andalso not (f1(2,0)) andalso not (f1(~1,3)) andalso not (f1(max + 1,4)) andalso not (f1(5,max + 1)) = true), 15 | 16 | ("2", f2((3,4),(3,4)) andalso f2((1,5),(1,6)) andalso f2((2,3),(1,3)) andalso f2((3,4),(2,3)) andalso f2((4,5),(5,6)) andalso not(f2((2,3),(4,5))) andalso f2((max + 100, 1),(1, max + 20)) = true), 17 | 18 | ("3.0", f3([]) = true), 19 | ("3.1", f3([(1,1)]) = true), 20 | ("3.2", f3([(max,max)]) = true), 21 | ("3.3", f3([(1,1),(1,2),(1,3),(7,1),(7,6),(7,7)]) = true), 22 | ("3.4", f3([(0,1),(1,1),(1,2),(1,3),(7,1),(7,6),(7,7)]) = false), 23 | ("3.5", f3([(1,0),(1,2),(1,3),(7,1),(7,6),(7,7)]) = false), 24 | ("3.6", f3([(1,1),(1,2),(1,3),(7,1),(7,6),(7,7),(1,~7)]) = false), 25 | ("3.7", f3([(1,1),(1,2),(1,3),(7,1),(7,6),(7,7),(~3,6)]) = false), 26 | ("3.8", f3([(1,1),(1,2),(1,3),(max + 1,2),(7,1),(7,6),(7,7)]) = false), 27 | ("3.9", f3([(1,1),(1,2),(1,3),(3, max + 10),(7,1),(7,6),(7,7)]) = false), 28 | 29 | ("4.0", f4([]) = true), 30 | ("4.1", f4([(1,2)]) = true), 31 | ("4.2", f4([(3,3)]) = false), 32 | ("4.3", f4([(2,3),(3,4),(4,5),(7,8),(max + 3,4),(~1,~max)]) = true), 33 | ("4.4", f4([(1,1),(2,3),(3,4),(4,5),(7,8),(max + 3,4),(~1,~max)]) = false), 34 | ("4.5", f4([(2,3),(3,4),(4,5),(7,8),(max + 3,4),(~1,~max),(2,2)]) = false), 35 | ("4.6", f4([(2,3),(3,4),(4,5),(max,max),(7,8),(max + 3,4),(~1,~max)]) = false), 36 | ("4.7", f4([(2,3),(3,4),(4,5),(7,8),(3,3),(max + 3,4),(~1,~max)]) = false), 37 | 38 | ("5.0", f5(0) = []), 39 | ("5.1", f5(1) = [(1,1)]), 40 | ("5.2", f5(2) = [(2,2),(1,2),(2,1)]), 41 | ("5.3", f5(3) = [(3,3),(2,3),(3,2),(1,3),(3,1)]), 42 | 43 | ("6.0", f6([]) = false), 44 | ("6.1", f6([(2,3)]) = true), 45 | ("6.2", f6([(2,2),(1,2),(2,1)]) = true), 46 | ("6.3", f6([(3,3),(2,3),(3,2),(1,3),(3,1)]) = true), 47 | ("6.4", f6([(1,1),(3,3),(2,3),(3,2),(1,3),(3,1)]) = false), 48 | ("6.5", f6([(3,3),(2,3),(5,7),(3,2),(1,3),(3,1)]) = false), 49 | ("6.6", f6([(3,3),(2,3),(3,2),(1,3),(3,1),(4,5)]) = false), 50 | 51 | ("7.0", f7([]) = false), 52 | ("7.1", f7([(2,3)]) = true), 53 | ("7.2", f7([(2,3),(3,5)]) = true), 54 | ("7.3", f7([(1,1),(1,4),(4,5),(5,6),(6,7),(7,6)]) = true), 55 | ("7.4", f7([(1,2),(1,1),(1,4),(4,5),(5,6),(6,7),(7,6)]) = false), 56 | ("7.5", f7([(1,1),(1,4),(4,5),(5,6),(6,7),(7,6),(7,7)]) = false), 57 | ("7.6", f7([(1,1),(1,4),(4,5),(5,4),(5,6),(6,7),(7,8)]) = false), 58 | 59 | ("8.0", f8(0,0) = [] andalso f8(5,5) = []), 60 | ("8.1", f8(1,2) = [(1,2)]), 61 | ("8.2", f8(1,4) = [(1,2),(2,3),(3,4)]), 62 | 63 | ("9.0", f9([]) = false), 64 | ("9.1", f9([(2,3)]) = true), 65 | ("9.2", f9([(2,3),(3,5)]) = true), 66 | ("9.3", f9([(1,1),(1,1),(1,1),(1,1),(1,1),(1,1),(1,1)]) = true), 67 | ("9.4", f9([(1,1),(1,4),(4,5),(5,6),(6,7),(7,6)]) = true), 68 | ("9.5", f9([(2,3),(5,3)]) = true), 69 | ("9.6", f9([(5,4),(5,3)]) = true), 70 | ("9.7", f9([(1,2),(1,1),(1,4),(4,5),(5,6),(6,7),(7,6)]) = true), 71 | ("9.8", f9([(1,2),(1,1),(4,1),(5,4),(6,5),(7,6),(7,6)]) = true), 72 | ("9.9", f9([(1,1),(1,4),(4,5),(5,6),(6,7),(7,6),(7,7)]) = false), 73 | ("9.10", f9([(1,1),(1,4),(4,5),(5,4),(5,5),(5,6),(6,7),(7,8)]) = false) 74 | ]; 75 | 76 | print "\n------------------------------------------------\n"; 77 | fun all_tests(tests) = 78 | let fun helper(tests: (string*bool) list, all_passed) = 79 | case tests of 80 | [] => all_passed 81 | | (st, true)::rest => helper(rest, all_passed) 82 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 83 | in 84 | helper(tests, true) 85 | end; 86 | 87 | case all_tests(tests) of 88 | true => print "--------------EVERY TESTS PASSED-------------\n" 89 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 90 | -------------------------------------------------------------------------------- /2005/hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw2/hw2.pdf -------------------------------------------------------------------------------- /2005/hw2/johnson_hw2.sml: -------------------------------------------------------------------------------- 1 | type bone = int * int 2 | 3 | type hand = bone list 4 | type deck = bone list 5 | type layout = bone list 6 | 7 | datatype move = PlayFirst of bone 8 | | PlayLeft of bone 9 | | PlayRight of bone 10 | | PassDraw 11 | 12 | exception BadMove 13 | 14 | fun find_playable(h,s) = 15 | case h of 16 | [] => NONE 17 | | (s1,s2)::xs' => if s1 = s orelse s2 = s 18 | then SOME (s1,s2) 19 | else find_playable(xs',s) 20 | 21 | fun without_bone(h,b) = 22 | let fun helper(h,acc) = 23 | case h of 24 | [] => acc 25 | | (s1,s2)::xs' => if (s1,s2) = b orelse (s2,s1) = b 26 | then List.concat(acc::xs'::[]) 27 | else helper(xs',List.concat(acc::[(s1,s2)]::[])) 28 | in helper(h,[]) 29 | end 30 | 31 | fun layout_summary(l) = 32 | let fun helper(l,pl) = 33 | case l of 34 | (_,s2)::[] => SOME (pl,s2) 35 | | _::xs' => helper(xs',pl) 36 | in case l of 37 | [] => NONE 38 | | x::[] => SOME x 39 | | (s1,_)::xs' => helper(xs',s1) 40 | end 41 | 42 | fun best_move(l,h) = 43 | case (l,h) of 44 | ([],[]) => PassDraw 45 | | ([],b::bs') => PlayFirst b 46 | | (l,h) => 47 | let val SOME layout = layout_summary(l) 48 | val left = (#1 layout) 49 | val right = (#2 layout) 50 | in 51 | case(find_playable(h,left),find_playable(h,right)) of 52 | (NONE,NONE) => PassDraw 53 | | (SOME b, _) => PlayLeft b 54 | | (_, SOME b) => PlayRight b 55 | end 56 | 57 | fun do_move(l,d,h,m) = 58 | let fun helper(f, (s1,s2)) = 59 | case (List.find(fn(x) => x = (s1,s2) orelse x = (s2,s1)) h) of 60 | NONE => raise BadMove 61 | | SOME b => f(b) 62 | fun get_left(l) = #1 (valOf (layout_summary(l))) 63 | fun get_right(l) = #2 (valOf (layout_summary(l))) 64 | in case (l,d,h,m) of 65 | (_,x::xs',h,PassDraw) => (l,xs',x::h) 66 | | (_,[],h,PassDraw) => (l,[],h) 67 | | (x::xs',_,_,PlayFirst b) => raise BadMove 68 | | ([],_,h,PlayFirst b) => helper((fn(rb) => ([rb],d,without_bone(h,rb))), b) 69 | | ([],_,_,PlayLeft _) => raise BadMove 70 | | ([],_,_,PlayRight _) => raise BadMove 71 | | (l,_,h,PlayLeft b) => helper((fn(s1,s2) => case (s1 = get_left(l), s2 = get_left(l)) of 72 | (false,false) => raise BadMove 73 | | (true,_) => ((s2,s1)::l,d,without_bone(h,(s1,s2))) 74 | | (_,true) => ((s1,s2)::l,d,without_bone(h,(s1,s2)))), b) 75 | | (l,_,h,PlayRight b) => helper((fn(s1,s2) => case (s1 = get_right(l), s2 = get_right(l)) of 76 | (false,false) => raise BadMove 77 | | (true,_) => (l@[(s1,s2)],d,without_bone(h,(s1,s2))) 78 | | (_,true) => (l@[(s2,s1)],d,without_bone(h,(s1,s2)))), b) 79 | end 80 | 81 | -------------------------------------------------------------------------------- /2005/hw2/johnson_hw2_test.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw2.sml"; 2 | val name_hw = "2005 - Assignment Two" 3 | val f1 = find_playable 4 | val f2 = without_bone 5 | val f3 = layout_summary 6 | val f4 = best_move 7 | val f5 = do_move 8 | 9 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 10 | val tests = [ 11 | ("1.0", f1([], 3) = NONE), 12 | ("1.1", f1([(1,1)], 1) = SOME (1,1)), 13 | ("1.2", f1([(1,1)], 2) = NONE), 14 | ("1.3", f1([(1,1),(2,1),(3,4)], 1) = SOME (1,1)), 15 | ("1.4", f1([(1,1),(2,1),(3,4)], 2) = SOME (2,1)), 16 | ("1.5", f1([(1,1),(2,1),(3,4)], 3) = SOME (3,4)), 17 | ("1.6", f1([(1,1),(2,1),(3,4)], 4) = SOME (3,4)), 18 | ("1.7", f1([(1,1),(2,1),(3,4)], 5) = NONE), 19 | 20 | ("2.0", f2([],(1,3)) = []), 21 | ("2.1", f2([(2,3)],(2,3)) = [] andalso f2([(3,2)],(2,3)) = [] andalso f2([(2,3)],(3,2)) = []), 22 | ("2.2", f2([(5,6),(3,4),(1,2)],(5,6)) = [(3,4),(1,2)] andalso f2([(5,6),(3,4),(1,2)],(3,4)) = [(5,6),(1,2)] andalso f2([(5,6),(3,4),(1,2)],(1,2)) = [(5,6),(3,4)]), 23 | 24 | ("2.3", f2([(5,6),(3,4),(1,2),(5,6)],(5,6)) = [(3,4),(1,2),(5,6)] andalso f2([(5,6),(3,4),(3,4),(1,2)],(3,4)) = [(5,6),(3,4),(1,2)] andalso f2([(5,6),(1,2),(3,4),(1,2)],(1,2)) = [(5,6),(3,4),(1,2)]), 25 | 26 | ("3.0", f3([]) = NONE), 27 | ("3.1", f3([(1,7)]) = SOME (1,7)), 28 | ("3.2", f3([(1,1),(2,1)]) = SOME (1,1)), 29 | ("3.3", f3([(1,1),(2,1),(3,4)]) = SOME (1,4)), 30 | ("3.4", f3([(5,6),(3,4),(1,2),(5,6)]) = SOME (5,6)), 31 | 32 | ("4.0", f4([],[]) = PassDraw), 33 | ("4.1", f4([],[(1,2)]) = PlayFirst (1,2)), 34 | ("4.2", f4([(1,2)],[(1,2)]) = PlayLeft (1,2)), 35 | ("4.3", f4([(2,1)],[(1,2)]) = PlayLeft (1,2)), 36 | ("4.4", f4([(3,4),(4,6)],[(3,2)]) = PlayLeft (3,2)), 37 | ("4.5", f4([(3,4),(4,6)],[(1,3)]) = PlayLeft (1,3)), 38 | ("4.6", f4([(3,4),(4,6)],[(2,6)]) = PlayRight (2,6)), 39 | ("4.7", f4([(3,4),(4,6)],[(6,5)]) = PlayRight (6,5)), 40 | ("4.8", f4([(5,6),(3,4),(1,2),(3,4)],[(7,7)]) = PassDraw), 41 | 42 | (*a layout l, a deck d, a hand h, and a move m*) 43 | ("5.00", f5([],[],[],PassDraw) = ([],[],[])), 44 | ("5.01", f5([(1,2)],[],[],PassDraw) = ([(1,2)],[],[])), 45 | ("5.02", f5([],[],[(1,2)],PassDraw) = ([],[],[(1,2)])), 46 | ("5.03", f5([],[(1,2)],[],PassDraw) = ([],[],[(1,2)])), 47 | ("5.04", f5([],[(1,2),(3,4)],[],PassDraw) = ([],[(3,4)],[(1,2)])), 48 | 49 | ("5.10", f5([(2,3)],[],[(4,5)],PlayFirst(4,5)) = ([],[],[]) handle BadMove => true), 50 | ("5.11", f5([],[],[(3,6)],PlayFirst(4,5)) = ([],[],[]) handle BadMove => true), 51 | ("5.12", f5([],[],[(4,5)],PlayFirst(4,5)) = ([(4,5)],[],[])), 52 | 53 | ("5.20", f5([],[],[(4,5)],PlayRight(4,5)) = ([],[],[]) handle BadMove => true), 54 | ("5.21", f5([],[],[(4,5)],PlayLeft(4,5)) = ([],[],[]) handle BadMove => true), 55 | ("5.22", f5([(4,5)],[],[(4,5)],PlayRight(6,7)) = ([],[],[]) handle BadMove => true), 56 | ("5.23", f5([(4,5)],[],[(4,5)],PlayLeft(6,7)) = ([],[],[]) handle BadMove => true), 57 | ("5.24", f5([(4,5)],[],[(3,2)],PlayRight(3,2)) = ([],[],[]) handle BadMove => true), 58 | ("5.25", f5([(4,5)],[],[(3,2)],PlayLeft(3,2)) = ([],[],[]) handle BadMove => true), 59 | ("5.26", f5([(4,3)],[],[(3,2)],PlayRight(3,2)) = ([(4,3),(3,2)],[],[])), 60 | ("5.27", f5([(4,2)],[],[(3,2)],PlayRight(3,2)) = ([(4,2),(2,3)],[],[])), 61 | ("5.28", f5([(4,3)],[],[(5,4)],PlayLeft(5,4)) = ([(5,4),(4,3)],[],[])), 62 | ("5.29", f5([(4,3)],[],[(4,5)],PlayLeft(4,5)) = ([(5,4),(4,3)],[],[])), 63 | ("5.291", f5([(4,3)],[],[(2,3)],PlayRight(3,2)) = ([(4,3),(3,2)],[],[])), 64 | ("5.292", f5([(4,2)],[],[(2,3)],PlayRight(3,2)) = ([(4,2),(2,3)],[],[])), 65 | ("5.293", f5([(4,3)],[],[(4,5)],PlayLeft(5,4)) = ([(5,4),(4,3)],[],[])), 66 | ("5.294", f5([(4,3)],[],[(5,4)],PlayLeft(4,5)) = ([(5,4),(4,3)],[],[])), 67 | 68 | ("5.30", f5([(1,2)],[],[(5,2),(3,0)],PlayRight(5,2)) = ([(1,2),(2,5)],[],[(3,0)])) 69 | 70 | 71 | ]; 72 | 73 | print ("\n----------------------"^name_hw^"--------------------------\n"); 74 | fun all_tests(tests) = 75 | let fun helper(tests: (string*bool) list, all_passed) = 76 | case tests of 77 | [] => all_passed 78 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 79 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 80 | in 81 | helper(tests, true) 82 | end; 83 | 84 | case all_tests(tests) of 85 | true => print "--------------EVERY TESTS PASSED-------------\n" 86 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 87 | -------------------------------------------------------------------------------- /2005/hw3/hw3-provided.sml: -------------------------------------------------------------------------------- 1 | signature GRAPHER = sig 2 | val graph_window 3 | :int * int -> 4 | real * real -> 5 | real * real -> 6 | (real -> real) 7 | -> unit 8 | 9 | val graph 10 | :(real -> real) -> unit 11 | end 12 | 13 | 14 | structure Grapher :> GRAPHER = struct 15 | 16 | fun make_columns (height, values, xaxis, yaxis) = 17 | let fun mc (x, dot) = 18 | let fun helper (pos) = 19 | case pos of 20 | 0 => [] 21 | | _ => (if SOME pos = dot then #"o" else 22 | if x = yaxis andalso pos = xaxis then #"+" else 23 | if pos = xaxis then #"-" else 24 | if x = yaxis then #"|" else 25 | #" ")::helper(pos-1) 26 | in 27 | helper(height) 28 | end 29 | fun loop (x, vals) = 30 | case vals of 31 | [] => [] 32 | | y::rest => mc(x,y)::loop(x+1,rest) 33 | in loop(0, values) end 34 | 35 | fun convert_to_strings (cols, number) = 36 | case number of 37 | 0 => [] 38 | | _ => (implode (List.map hd cols) ^ "\n") 39 | ::convert_to_strings(List.map tl cols, number-1) 40 | 41 | fun deltas (width, height, xmin, xmax, ymin, ymax) = 42 | let val dx = (xmax-xmin)/(Real.fromInt width) 43 | val dy = (ymax-ymin)/(Real.fromInt height) 44 | in (dx,dy) end 45 | 46 | fun toInt x = 47 | SOME (Real.toInt IEEEReal.TO_NEGINF x) handle 48 | overflow => NONE 49 | 50 | fun create_values (f, width, height, xmin, xmax, ymin, ymax) = 51 | let val (dx,dy) = deltas(width,height,xmin,xmax,ymin,ymax) 52 | val dy = (ymax-ymin)/(Real.fromInt height) 53 | fun helper (pos, x) = 54 | if pos = width 55 | then [] 56 | else toInt((f(x)-ymin)/dy+1.0)::helper(pos+1, x+dx) 57 | in helper(0, xmin) end 58 | 59 | fun graph_draw (f, width, height, xmin, xmax, ymin, ymax) = 60 | let val (dx,dy) = deltas (width, height, xmin, xmax, ymin, ymax) 61 | val values = create_values (f,width,height,xmin,xmax,ymin,ymax) 62 | val xaxis = valOf (toInt ((0.0 - ymin)/dy + 1.0)) 63 | val yaxis = valOf (toInt ((0.0 - xmin)/dx)) 64 | val columns = make_columns (height, values, xaxis, yaxis); 65 | val strings = convert_to_strings (columns, height); 66 | in 67 | List.app print strings 68 | end 69 | 70 | fun graph_window (width,height) (xmin,xmax) (ymin,ymax) f = 71 | graph_draw (f, width, height, xmin, xmax, ymin, ymax) 72 | 73 | val graph = graph_window (68,29) (~10.0, 10.0) (~10.0, 10.0); 74 | 75 | end 76 | -------------------------------------------------------------------------------- /2005/hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw3/hw3.pdf -------------------------------------------------------------------------------- /2005/hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | (*JOHNSON hw3*) 2 | type bone = int * int 3 | type line = bone list 4 | datatype lineop = 5 | PushRight (*Take element from left, push it onto right *) 6 | | PushLeft (*Take element from right, push it onto left*) 7 | | SwapFirst (* Take first bone from each line and swap them*) 8 | | ApplyRight of bone -> bone (*Apply function to first bone on the right*) 9 | | ApplyLeft of bone -> bone (*Apply function to first bone on the left*) 10 | 11 | type lineprog = lineop list 12 | 13 | (* 14 | val lineop_func = fn : lineop -> bone list * bone list -> bone list * bone list 15 | val lineprog_func = fn 16 | : lineop list -> bone list * bone list -> bone list * bone list 17 | val pushn_right_safe = fn : int -> lineop list 18 | val pushn_right_block = fn : int -> lineop list 19 | val lineprog_mirror = fn : lineop list -> lineop list 20 | val pushn_left_safe = fn : int -> lineop list 21 | val pushn_left_block = fn : int -> lineop list 22 | val derivative = fn : (real -> real) -> real -> real 23 | val def_integral = fn : (real -> real) -> real -> real -> real 24 | val integral = fn : (real -> real) -> real -> real 25 | *) 26 | 27 | fun lineop_func lop bpair = 28 | let fun helper (left,right) = 29 | case (lop,left,right) of 30 | (PushRight,[],_) => raise Empty 31 | | (PushLeft,_,[]) => raise Empty 32 | | (SwapFirst,[],_) => raise Empty 33 | | (SwapFirst,_,[]) => raise Empty 34 | | (ApplyRight f, _, []) => raise Empty 35 | | (ApplyLeft f, [],_) => raise Empty 36 | | (PushRight,x::xs',right) => (xs',x::right) 37 | | (PushLeft,left,x::xs') => (x::left,xs') 38 | | (SwapFirst,x::xs',y::ys') => (y::xs',x::ys') 39 | | (ApplyRight f, left, x::xs') => (left,f(x)::xs') 40 | | (ApplyLeft f, y::ys',right) => (f(y)::ys',right) 41 | in helper bpair 42 | end 43 | 44 | fun lineprog_func prog pair = List.foldl (fn(f,acc) => f acc) pair (List.map lineop_func prog); 45 | (* 46 | fun lineprog_func prog pair = 47 | case prog of 48 | x::[] => pair 49 | | x::xs' => lineprog_func xs' (lineop_func x pair) 50 | 51 | val fl1 = (List.foldl (fn(f,acc) => f acc)) o (List.map lineop_func p); 52 | *) 53 | 54 | fun pushn_right_safe n = 55 | case (n, n > 0) of 56 | (_,false) => [] 57 | | (1,true) => [PushRight, ApplyRight(fn(x,y)=>(y,x))] 58 | | (n,true) => PushRight::ApplyRight(fn(x,y)=>(y,x))::(pushn_right_safe (n-1)) 59 | 60 | fun pushn_right_block n = 61 | let fun push_right m = 62 | case (m, m > 0) of 63 | (_, false) => [] 64 | | (m, true) => PushRight::(push_right (m-1)) 65 | fun swap_left m = 66 | case (m, m > 0) of 67 | (_, false) => [SwapFirst] 68 | | (m, true) => SwapFirst::PushLeft::(swap_left (m-1)) 69 | in case (n, n < 2,n < 1) of 70 | (_,_,true) => [] 71 | | (1,_,false) => [PushRight] 72 | | (_,false,_) => push_right(n-1)@swap_left(n-2)@pushn_right_block(n-1) 73 | end 74 | 75 | fun lineprog_mirror prog = List.map(fn(e)=> case e of 76 | PushRight => PushLeft 77 | | PushLeft => PushRight 78 | | ApplyRight f => ApplyLeft f 79 | | ApplyLeft f => ApplyRight f 80 | | _ => e) prog 81 | 82 | val pushn_left_safe = lineprog_mirror o pushn_right_safe 83 | val pushn_left_block = lineprog_mirror o pushn_right_block 84 | 85 | fun lineprog_optimize prog = 86 | case prog of 87 | [] => [] 88 | | x::[] => [x] 89 | | PushRight::PushLeft::xs'' => lineprog_optimize xs'' 90 | | PushLeft::PushRight::xs'' => lineprog_optimize xs'' 91 | | SwapFirst::SwapFirst::xs'' => lineprog_optimize xs'' 92 | | x::xs'::xs'' => x::xs'::(lineprog_optimize xs'') 93 | 94 | val bignumber = 100000.0 95 | val smallnumber = 1.0/bignumber 96 | fun derivative f x = ((f (x + smallnumber)) - (f x))/smallnumber 97 | 98 | fun def_integral (f:real->real) a b = 99 | if (a + smallnumber) < b 100 | then (f a) + (def_integral f (a+smallnumber) b) 101 | else f a 102 | 103 | fun integral f = def_integral f 0.0 104 | 105 | -------------------------------------------------------------------------------- /2005/hw3/johnson_hw3_test.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw3.sml"; 2 | val name_hw = "2005 - Assignment Three" 3 | 4 | val f1 = lineop_func 5 | val f2 = lineprog_func 6 | val f3 = pushn_right_safe 7 | val f4 = pushn_right_block 8 | 9 | val a_pair = ([(1,2),(6,7),(3,4),(8,9)],[(3,4),(6,7),(1,2),(8,9)]) 10 | val a_6pair = ([(1,2),(2,3),(4,5),(6,7),(3,4),(8,9)],[(13,14),(16,17),(11,12),(18,19),(21,22),(23,24)]) 11 | val a_100pair = ([(1,001),(1,002),(1,003),(1,004),(1,005),(1,006),(1,007),(1,008),(1,009),(1,010),(1,011),(1,012),(1,013),(1,014),(1,015),(1,016),(1,017),(1,018),(1,019),(1,020),(1,021),(1,022),(1,023),(1,024),(1,025),(1,026),(1,027),(1,028),(1,029),(1,030),(1,031),(1,032),(1,033),(1,034),(1,035),(1,036),(1,037),(1,038),(1,039),(1,040),(1,041),(1,042),(1,043),(1,044),(1,045),(1,046),(1,047),(1,048),(1,049),(1,050),(1,051),(1,052),(1,053),(1,054),(1,055),(1,056),(1,057),(1,058),(1,059),(1,060),(1,061),(1,062),(1,063),(1,064),(1,065),(1,066),(1,067),(1,068),(1,069),(1,070),(1,071),(1,072),(1,073),(1,074),(1,075),(1,076),(1,077),(1,078),(1,079),(1,080),(1,081),(1,082),(1,083),(1,084),(1,085),(1,086),(1,087),(1,088),(1,089),(1,090),(1,091),(1,092),(1,093),(1,094),(1,095),(1,096),(1,097),(1,098),(1,099),(1,100)],[(1,001),(1,002),(1,003),(1,004),(1,005),(1,006),(1,007),(1,008),(1,009),(1,010),(1,011),(1,012),(1,013),(1,014),(1,015),(1,016),(1,017),(1,018),(1,019),(1,020),(1,021),(1,022),(1,023),(1,024),(1,025),(1,026),(1,027),(1,028),(1,029),(1,030),(1,031),(1,032),(1,033),(1,034),(1,035),(1,036),(1,037),(1,038),(1,039),(1,040),(1,041),(1,042),(1,043),(1,044),(1,045),(1,046),(1,047),(1,048),(1,049),(1,050),(1,051),(1,052),(1,053),(1,054),(1,055),(1,056),(1,057),(1,058),(1,059),(1,060),(1,061),(1,062),(1,063),(1,064),(1,065),(1,066),(1,067),(1,068),(1,069),(1,070),(1,071),(1,072),(1,073),(1,074),(1,075),(1,076),(1,077),(1,078),(1,079),(1,080),(1,081),(1,082),(1,083),(1,084),(1,085),(1,086),(1,087),(1,088),(1,089),(1,090),(1,091),(1,092),(1,093),(1,094),(1,095),(1,096),(1,097),(1,098),(1,099),(1,100)]) 12 | 13 | val a_3prog = [PushRight,SwapFirst,PushRight,SwapFirst, 14 | PushLeft,SwapFirst, 15 | PushRight,PushRight] 16 | val a_4prog = [PushRight, SwapFirst, PushRight, SwapFirst, PushRight, SwapFirst, 17 | PushLeft, SwapFirst, PushLeft, SwapFirst, 18 | PushRight, SwapFirst, 19 | PushRight, PushRight] 20 | 21 | fun compare lop1 lop2 = 22 | case (lop1,lop2) of 23 | (PushRight,PushRight) => true 24 | | (PushLeft,PushLeft) => true 25 | | (SwapFirst,SwapFirst) => true 26 | | (ApplyRight _, ApplyRight _) => true 27 | | (ApplyLeft _, ApplyLeft _) => true 28 | | _ => false 29 | fun comparelists(l1, l2) = List.foldl(fn((x,y),acc) => compare x y) true (ListPair.zip(l1,l2)) 30 | 31 | fun compare_pairs(p1,(p2l,p2r),n) = 32 | let val left = List.drop(p2r,n) 33 | val right = List.take(p2r,n)@p2l 34 | in p1 = (left,right) 35 | end 36 | 37 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 38 | val tests = [ 39 | ("1.00", f1 PushRight ([],[]) <> ([],[]) handle Empty => true), 40 | ("1.01", f1 PushLeft ([],[]) <> ([],[]) handle Empty => true), 41 | ("1.02", f1 PushRight ([],[(1,2)]) <> ([],[]) handle Empty => true), 42 | ("1.03", f1 PushLeft ([(1,2)],[]) <> ([],[]) handle Empty => true), 43 | ("1.04", f1 SwapFirst ([],[]) <> ([],[]) handle Empty => true), 44 | ("1.05", f1 SwapFirst ([(1,2)],[]) <> ([],[]) handle Empty => true), 45 | ("1.06", f1 SwapFirst ([],[(1,2)]) <> ([],[]) handle Empty => true), 46 | ("1.07", f1 (ApplyRight(fn(x) => x)) ([],[]) <> ([],[]) handle Empty => true), 47 | ("1.08", f1 (ApplyLeft (fn(x) => x)) ([],[]) <> ([],[]) handle Empty => true), 48 | ("1.09", f1 (ApplyRight(fn(x) => x)) ([(1,2)],[]) <> ([],[]) handle Empty => true), 49 | ("1.10", f1 (ApplyLeft (fn(x) => x)) ([],[(1,2)]) <> ([],[]) handle Empty => true), 50 | 51 | ("1.20", f1 PushRight ([(1,2)],[]) = ([],[(1,2)])), 52 | ("1.21", f1 PushRight ([(1,2),(2,4)],[]) = ([(2,4)],[(1,2)])), 53 | ("1.22", f1 PushLeft ([],[(1,2)]) = ([(1,2)],[])), 54 | ("1.23", f1 PushLeft ([],[(1,2),(2,4)]) = ([(1,2)],[(2,4)])), 55 | ("1.24", f1 PushRight ([(1,2)],[]) = ([],[(1,2)])), 56 | 57 | ("1.30", f1 SwapFirst ([(1,2)],[(3,4)]) = ([(3,4)],[(1,2)])), 58 | ("1.31", f1 SwapFirst ([(1,2),(6,7)],[(3,4),(8,9)]) = ([(3,4),(6,7)],[(1,2),(8,9)])), 59 | 60 | ("1.40", f1 (ApplyRight(fn(x) => x)) ([],[(1,1)]) = ([],[(1,1)])), 61 | ("1.41", f1 (ApplyLeft(fn(x) => x)) ([(1,1)],[]) = ([(1,1)],[])), 62 | ("1.42", f1 (ApplyRight(fn(x) => x)) ([(2,2)],[(1,1)]) = ([(2,2)],[(1,1)])), 63 | ("1.43", f1 (ApplyLeft(fn(x) => x)) ([(2,2)],[(1,1)]) = ([(2,2)],[(1,1)])), 64 | ("1.44", f1 (ApplyRight(fn(x) => x)) ([(2,2)],[(1,1),(3,4)]) = ([(2,2)],[(1,1),(3,4)])), 65 | ("1.45", f1 (ApplyLeft(fn(x) => x)) ([(2,2),(4,5)],[(1,1)]) = ([(2,2),(4,5)],[(1,1)])), 66 | ("1.46", f1 (ApplyRight(fn(x,y) => (y,x))) ([(2,2)],[(1,2),(3,4)]) = ([(2,2)],[(2,1),(3,4)])), 67 | ("1.47", f1 (ApplyLeft(fn(x,y) => (y,x))) ([(2,3),(4,5)],[(1,1)]) = ([(3,2),(4,5)],[(1,1)])), 68 | ("1.48", f1 (ApplyRight(fn(x,y) => (y,x*4))) ([(2,2)],[(1,2),(3,4)]) = ([(2,2)],[(2,4),(3,4)])), 69 | ("1.49", f1 (ApplyLeft(fn(x,y) => (y,x*4))) ([(2,3),(4,5)],[(1,1)]) = ([(3,8),(4,5)],[(1,1)])), 70 | ("2.00", f2 [PushRight] ([(1,1)],[]) = ([],[(1,1)])), 71 | ("2.01", f2 [PushRight,PushLeft,PushRight] ([(1,1)],[]) = ([],[(1,1)])), 72 | ("2.02", f2 [SwapFirst,PushRight] ([(1,1)],[(2,2)]) = ([],[(2,2),(1,1)])), 73 | ("2.03", f2 [PushRight,PushRight,SwapFirst, ApplyRight(fn(x,y)=>(y,x)), ApplyLeft(fn(x,y)=>(2*y,3*x))] ([(1,2),(6,7),(3,4),(8,9)],[(3,4),(6,7),(1,2),(8,9)]) = ([(14,18),(8,9)],[(4,3),(1,2),(3,4),(6,7),(1,2),(8,9)])), 74 | 75 | ("3.00", comparelists(f3 0, [])), 76 | ("3.01", comparelists(f3 ~1, [])), 77 | ("3.02", comparelists(f3 1, [PushRight, ApplyRight(fn(x,y)=>(y,x))])), 78 | ("3.03", comparelists(f3 5, [PushRight, ApplyRight(fn(x,y)=>(y,x)),PushRight, ApplyRight(fn(x,y)=>(y,x)),PushRight, ApplyRight(fn(x,y)=>(y,x)),PushRight, ApplyRight(fn(x,y)=>(y,x)),PushRight, ApplyRight(fn(x,y)=>(y,x))])), 79 | 80 | ("4.00", comparelists((f4 0),[])), 81 | ("4.01", comparelists((f4 ~5),[])), 82 | ("4.02", comparelists((f4 1),[PushRight])), 83 | ("4.03", comparelists((f4 2),[PushRight,SwapFirst]@(f4 1))), 84 | ("4.04", comparelists((f4 3),a_3prog@(f4 2))), 85 | ("4.05", comparelists((f4 4),a_4prog@(f4 3))), 86 | 87 | ("4.10", compare_pairs(f2 (f4 0) a_100pair, a_100pair,0)), 88 | ("4.10", compare_pairs(f2 (f4 1) a_100pair, a_100pair,1)), 89 | ("4.10", compare_pairs(f2 (f4 2) a_100pair, a_100pair,2)), 90 | ("4.10", compare_pairs(f2 (f4 3) a_100pair, a_100pair,3)), 91 | ("4.10", compare_pairs(f2 (f4 4) a_100pair, a_100pair,4)), 92 | ("4.10", compare_pairs(f2 (f4 5) a_100pair, a_100pair,5)), 93 | ("4.10", compare_pairs(f2 (f4 95) a_100pair, a_100pair,95)), 94 | ("4.10", compare_pairs(f2 (f4 96) a_100pair, a_100pair,96)), 95 | ("4.10", compare_pairs(f2 (f4 97) a_100pair, a_100pair,97)), 96 | ("4.10", compare_pairs(f2 (f4 98) a_100pair, a_100pair,98)), 97 | ("4.10", compare_pairs(f2 (f4 99) a_100pair, a_100pair,99)), 98 | ("4.10", compare_pairs(f2 (f4 100) a_100pair, a_100pair,100)) 99 | ]; 100 | 101 | print ("\n----------------------"^name_hw^"--------------------------\n"); (*Name display to assert correct test file is running*) 102 | fun all_tests(tests) = 103 | let fun helper(tests: (string*bool) list, all_passed) = 104 | case tests of 105 | [] => all_passed 106 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 107 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 108 | in 109 | helper(tests, true) 110 | end; 111 | 112 | case all_tests(tests) of 113 | true => print ((Int.toString (List.length(tests))) ^ "--TESTS RUN------------EVERY TESTS PASSED-------------\n") 114 | 115 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 116 | -------------------------------------------------------------------------------- /2005/hw4/hw4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw4/hw4.pdf -------------------------------------------------------------------------------- /2005/hw5/hw5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw5/hw5.pdf -------------------------------------------------------------------------------- /2005/hw5/hw5provided.scm: -------------------------------------------------------------------------------- 1 | ;; A CSE341 Mini-Scheme Interpreter for the language "MiniScheme" 2 | ;; Skeleton Code 3 | ;; Be sure you understand this code before writing your solutions. This will 4 | ;; save you a lot of time since most of the code is implemented for you! 5 | 6 | 7 | ;;---------------DO NOT MODIFY CODE BELOW HERE------------------------------------ 8 | 9 | ;;helper function -- removes a variable from an environment, 10 | ;;returning a copy of the environment with that variable instance(s) removed. 11 | ;;Allows us to implement scheme-like define semantics of "mutate the existing 12 | ;;binding if there is one" 13 | (define (env-copy-remove e v) 14 | (cond ((null? e) 15 | '()) 16 | (else 17 | (if (eq? (caar e) v) 18 | (env-copy-remove (cdr e) v) 19 | (cons (car e) 20 | (env-copy-remove (cdr e) v)))))) 21 | 22 | ;;Updates the inputted environment with a new MiniScheme variable and its value. 23 | ;;Use this function for evaluating Define sentences 24 | (define (add-define! var val env) 25 | (let ((tmp (env-copy-remove env var))) ;;tmp has curr env with var removed 26 | (set-car! env (list var val)) 27 | (set-cdr! env tmp) 28 | 'ok)) 29 | 30 | ;;returns true if the argument is a minischeme constant 31 | (define constant? 32 | (lambda (expr) 33 | (or (boolean? expr) (number? expr)))) 34 | 35 | ;;returns true if the argument is a minischeme variable 36 | (define variable? 37 | (lambda (expr) 38 | (symbol? expr))) 39 | 40 | ;;Makes a MiniScheme closure out of a lambda's arguments, body, and environment. 41 | ;;A closure is represented as a list where the first value is 'closure, 42 | ;;the second is the lambda's arguments, 3rd is the lambda's body, and 4th is 43 | ;;the environment the lambda was defined in. 44 | (define make-closure 45 | (lambda (args body env) 46 | (list 'closure args body env))) 47 | 48 | ;;returns true if the argument is a MiniScheme closure 49 | (define closure? 50 | (lambda (expr) 51 | (and (pair? expr) 52 | (eq? (car expr) 'closure)))) 53 | 54 | ;;returns the lambda's arguments from minischeme closure 55 | (define closure-args 56 | (lambda (func) 57 | (cadr func))) 58 | 59 | ;;returns the lambda's body from a minischeme closure 60 | (define closure-body 61 | (lambda (func) 62 | (caddr func))) 63 | 64 | ;;returns the environment from a minischeme closure 65 | (define closure-env 66 | (lambda (func) 67 | (cadddr func))) 68 | 69 | ;;returns true if the argument is a minischeme "if" expression 70 | (define if? 71 | (lambda (expr) 72 | (eq? (car expr) 'if))) 73 | 74 | ;;returns the first minischeme expression in an "if" expression 75 | (define if-condition 76 | (lambda (expr) 77 | (cadr expr))) 78 | 79 | ;;returns the second minischeme expression in an "if" expression 80 | (define if-consequent 81 | (lambda (expr) 82 | (caddr expr))) 83 | 84 | ;;returns the 3rd minischeme expression in an "if" expression 85 | (define if-alternative 86 | (lambda (expr) 87 | (cadddr expr))) 88 | 89 | ;;returns true if the argument is a minischeme "define" sentence 90 | (define define? 91 | (lambda (expr) 92 | (eq? (car expr) 'define))) 93 | 94 | ;;returns the minischeme variable in a "define" sentence 95 | (define define-var 96 | (lambda (expr) 97 | (cadr expr))) 98 | 99 | ;;returns the minischeme value in a "define" sentence 100 | (define define-val 101 | (lambda (expr) 102 | (caddr expr))) 103 | 104 | ;;returns true if the argument is a minischeme "lambda" expression 105 | (define lambda? 106 | (lambda (expr) 107 | (eq? (car expr) 'lambda))) 108 | 109 | ;;returns the arguments of a minischeme "lambda" expression 110 | (define lambda-args 111 | (lambda (expr) 112 | (cadr expr))) 113 | 114 | ;;returns the body of a minischeme "lambda" expression 115 | (define lambda-body 116 | (lambda (expr) 117 | (caddr expr))) 118 | 119 | ;;returns the first minischeme expression in a function application expression. 120 | ;;This had better eval to a closure or a primitive op for evaluation to be correct! 121 | ;;example: returns from the sentence ( ... ) 122 | (define application-func 123 | (lambda (expr) 124 | (car expr))) 125 | 126 | ;;returns the rest of the minischeme expressions in a function application expression. 127 | ;;example: returns ... from the sentence ( ... ) 128 | (define application-args 129 | (lambda (expr) 130 | (cdr expr))) 131 | 132 | ;;The initial global environment. Maps a number of primitive Scheme functions 133 | ;;to MiniScheme variables so that MiniScheme sentences may use these primitive 134 | ;;operations. Uses Scheme quasiquote (shorthand is ` and shorthand for 135 | ;;unquote is ,) to bind the variable names to the Scheme primitive operations. 136 | ;;DO NOT MODIFY! 137 | (define global-env 138 | `((car ,car) (cdr ,cdr) (cons ,cons) (list, list) (empty_list ,()) 139 | (+ ,+) (- ,-) (* ,*) (/ ,/) (> ,>) (= , =))) 140 | 141 | ;;---------------------END DO NOT MODIFY-------------------------------------- 142 | 143 | ;;For problem 4, add similar accessor routines for a let expression here 144 | ;;TODO 145 | 146 | ;;Given a MiniScheme expression and an environment, evaluate the expression 147 | ;;and return the result. 148 | (define (minischeme-eval expr env) 149 | (cond ( ;;TODO -- your cases go here, 1 case for each minischeme sentence type 150 | 'NOT_IMPLEMENTED))) 151 | 152 | ;;Given a MiniScheme value (either a closure or a Scheme primitive), return 153 | ;;the result of evaluating this closure or primitive on the input list of vals 154 | (define (minischeme-apply closure_or_prim vals) 155 | (if (procedure? closure_or_prim) ;;case for primitve operations!! 156 | (apply closure_or_prim vals) ;;just apply the primitive to the vals 157 | ;;TODO -- your code for applying minischeme closures goes here 158 | 'NOT_IMPLEMENTED)) 159 | 160 | ;;The main REP loop for the MiniScheme interpreter. Execution of the interpreter 161 | ;;starts by executing this function. Feel free to play with this function, 162 | ;;but your final solution must NOT MODIFY it. 163 | (define MiniScheme 164 | (lambda () 165 | (letrec 166 | ((loop 167 | (lambda () 168 | (display "$ ") 169 | (let ((input (read))) ;;read is your simple parser 170 | (cond ((equal? input 'exit) ;;exit if "exit" is typed 171 | (void)) 172 | (else 173 | ;;display result of evaluating this sentence 174 | (display (minischeme-eval input global-env)) 175 | (newline) 176 | (loop))))))) 177 | (display "Welcome to MiniScheme!") 178 | (newline) 179 | (loop)))) -------------------------------------------------------------------------------- /2005/hw5/hw5test.txt: -------------------------------------------------------------------------------- 1 | (define x 3) 2 | (define foo (lambda (x) (lambda () x))) 3 | ((foo 5)) 4 | (define bar (let ((x 10)) (lambda () x))) 5 | (bar) 6 | (define foo2 (let ((x (lambda (x) (let ((x 25)) x)))) x)) 7 | (foo2 5) 8 | (+ ((lambda (x) x) 5) (* ((lambda (x) x) 10) (car (list 2 4)))) 9 | ((lambda (x y) (+ x y)) ((lambda () 3)) (* 4 5)) 10 | (define binomial1 (lambda (n k) (if (= n k) 1 (if (= k 0) 1 (+ (binomial1 (- n 1) (- k 1)) (binomial1 (- n 1) k)))))) 11 | (binomial1 15 10) 12 | (define factorial (lambda (n) (if (= n 0) 1 (* n (factorial (- n 1)))))) 13 | (factorial 10) 14 | (define x (let ((x factorial) (y binomial1) (z (lambda (a b) (+ (a 10) (b 15 10))))) (z x y))) 15 | x 16 | (define biglist (lambda (n acc) (if (= n 0) (cons 0 acc) (biglist (- n 1) (cons n acc))))) 17 | (define y (biglist 30 empty_list)) 18 | y 19 | (define sumlist (lambda (l length x acc) (if (= x length) (+ (car l) acc) (sumlist (cdr l) length (+ x 1) (+ (car l) acc))))) 20 | (sumlist y 31 1 0) -------------------------------------------------------------------------------- /2005/hw5/hw5test_output.txt: -------------------------------------------------------------------------------- 1 | Welcome to MiniScheme v2! 2 | $ open hw5test 3 | Successfully opened file: hw5test 4 | ok 5 | ok 6 | 5 7 | ok 8 | 10 9 | ok 10 | 25 11 | 25 12 | 23 13 | ok 14 | 3003 15 | ok 16 | 3628800 17 | ok 18 | 3631803 19 | ok 20 | ok 21 | (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30) 22 | ok 23 | 465 24 | $ -------------------------------------------------------------------------------- /2005/hw5/minischemev2.scm: -------------------------------------------------------------------------------- 1 | ;;The main REP loop for the MiniScheme interpreter. Execution of the interpreter 2 | ;;starts by executing this function. This interpreter allos you to read and 3 | ;;interpret a MiniScheme file! 4 | ;;How to read a file: normal REP execution remains the same. If you have a file 5 | ;;"myfile" that contains minischeme sentences seperate by newlines, then you can 6 | ;;execute "open myfile" at the minischeme prompt to read your file in line by line, 7 | ;;and evaluate your file's sentences. Execution continues normally afterwards. 8 | (define MiniScheme-v2 9 | (lambda () 10 | (letrec 11 | ((evaluate-string (lambda (str) (read (open-input-string str)))) 12 | (read-minischeme-file 13 | (lambda (fh) 14 | (let ((tmp (read-line fh))) 15 | (if (eof-object? tmp) 16 | 'eof 17 | (begin 18 | (display (minischeme-eval (evaluate-string tmp) global-env)) 19 | (newline) 20 | (read-minischeme-file fh)))))) 21 | (loop 22 | (lambda () 23 | (display "$ ") 24 | (let ((input (read))) ;;read is your simple parser 25 | (cond ((equal? input 'exit) ;; exit if "exit" is typed 26 | (void)) 27 | ((equal? input 'open) ;; file open case? 28 | (letrec ((file-name (symbol->string (read))) 29 | (file-handle 30 | (open-input-file file-name))) 31 | (begin 32 | (display "Successfully opened file: ") 33 | (display file-name) 34 | (newline) 35 | (read-minischeme-file file-handle) 36 | (loop)))) 37 | ;;do a normal REP from user input 38 | (else 39 | ;;display result of evaluating this sentence 40 | (display (minischeme-eval input global-env)) 41 | (newline) 42 | (loop))))))) 43 | (display "Welcome to MiniScheme v2!\n") 44 | (loop)))) -------------------------------------------------------------------------------- /2005/hw5/minischemev_2.scm: -------------------------------------------------------------------------------- 1 | ;;The main REP loop for the MiniScheme interpreter. Execution of the interpreter 2 | ;;starts by executing this function. This interpreter allos you to read and 3 | ;;interpret a MiniScheme file! 4 | ;;How to read a file: normal REP execution remains the same. If you have a file 5 | ;;"myfile" that contains minischeme sentences seperate by newlines, then you can 6 | ;;execute "open myfile" at the minischeme prompt to read your file in line by line, 7 | ;;and evaluate your file's sentences. Execution continues normally afterwards. 8 | (define MiniScheme-v2 9 | (lambda () 10 | (letrec 11 | ((evaluate-string (lambda (str) (read (open-input-string str)))) 12 | (read-minischeme-file 13 | (lambda (fh) 14 | (let ((tmp (read-line fh))) 15 | (if (eof-object? tmp) 16 | 'eof 17 | (begin 18 | (display (minischeme-eval (evaluate-string tmp) global-env)) 19 | (newline) 20 | (read-minischeme-file fh)))))) 21 | (loop 22 | (lambda () 23 | (display "$ ") 24 | (let ((input (read))) ;;read is your simple parser 25 | (cond ((equal? input 'exit) ;; exit if "exit" is typed 26 | (void)) 27 | ((equal? input 'open) ;; file open case? 28 | (letrec ((file-name (symbol->string (read))) 29 | (file-handle 30 | (open-input-file file-name))) 31 | (begin 32 | (display "Successfully opened file: ") 33 | (display file-name) 34 | (newline) 35 | (read-minischeme-file file-handle) 36 | (loop)))) 37 | ;;do a normal REP from user input 38 | (else 39 | ;;display result of evaluating this sentence 40 | (display (minischeme-eval input global-env)) 41 | (newline) 42 | (loop))))))) 43 | (display "Welcome to MiniScheme v2!\n") 44 | (loop)))) -------------------------------------------------------------------------------- /2005/hw6/hw6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005/hw6/hw6.pdf -------------------------------------------------------------------------------- /2005_autumn/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005_autumn/hw1/hw1.pdf -------------------------------------------------------------------------------- /2005_autumn/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | fun spherevolume r = 4.0/3.0*Math.pi*Math.pow(r,3.0) 2 | val squares = List.map (fn(x)=> x*x) 3 | fun repeat r n = if n <= 0 then [] else r::(repeat r (n-1)) 4 | fun repeatlist ls n = List.foldl (fn(x,acc)=> (repeat x n)@acc) [] ls 5 | fun ascending [] = false 6 | | ascending [x] = false 7 | | ascending (x::xs') = #2 (List.foldl (fn(y,(prev,res))=> (y,y>prev andalso res)) (x,true) xs') 8 | 9 | (* Previous implementations of above functions *) 10 | fun ascending_long [] = false 11 | | ascending_long [x] = false 12 | | ascending_long ls = 13 | let fun eval [x] = true 14 | | eval (x::x'::xs') = x v=var) en) of 20 | NONE => raise UnboundVariable 21 | | SOME (var,vl) => vl 22 | 23 | fun process_let e v_init vl_init en ls' = 24 | let val let_SML = List.foldl (fn(Bind (v,vl),acc)=> (v,eval vl acc)::acc) 25 | ((v_init, eval vl_init en)::en) 26 | ls' 27 | val let_Scheme = List.foldl (fn(Bind (v,vl),acc)=> acc@[(v,eval vl en)] handle UnboundVariable => acc@[(v,eval vl acc)]) 28 | [(v_init, eval vl_init en)] 29 | ls' 30 | in case type_of_eval of 31 | SML => eval e let_SML 32 | | Scheme => eval e (let_Scheme@en) 33 | end 34 | and eval ex en = 35 | case ex of 36 | Const a => a 37 | | Var a => lookup a en 38 | | `~a => ~(eval a en) 39 | | `+ (a,b) => (eval a en) + (eval b en) 40 | | `- (a,b) => (eval a en) - (eval b en) 41 | | `* (a,b) => (eval a en) * (eval b en) 42 | | `/ (a,b) => (eval a en) div (eval b en) 43 | | Let ([],_) => raise SyntaxError 44 | | Let ((Bind (v_init,vl_init))::ls',e) => process_let e v_init vl_init en ls' 45 | 46 | val e1 = Const 5; 47 | val e2 = `+(Const 5, Const 3); 48 | val e3 = `-(Const 5, Const 3); 49 | val e4 = `*(Const 5, Const 3); 50 | val e5 = `/(Const 4, Const 2); 51 | val e7 = `+(e2,e3); 52 | val e8 = `-(e2,e3); 53 | val e9 = `*(e2,e3); 54 | val e10 = `/(e2,e3); 55 | val e11 = `*(e7,e4); 56 | 57 | eval e1 [] = 5; 58 | eval e2 [] = 8; 59 | eval e3 [] = 2; 60 | eval e4 [] = 15; 61 | eval e5 [] = 2; 62 | eval e7 [] = 10; 63 | eval e8 [] = 6; 64 | eval e9 [] = 16; 65 | eval e10 [] = 4; 66 | eval e11 [] = 150; 67 | 68 | val e12 = "x"; 69 | val env1 = [("x",5), ("y",3)]; 70 | lookup e12 env1 = 5; 71 | 72 | val e13 = Var "x"; 73 | val e14 = Var "y"; 74 | 75 | val e15 = Const 5; 76 | val e16 = `+(e13, e14); 77 | val e17 = `-(e13, e14); 78 | val e18 = `*(e13, e14); 79 | val e19 = `/(e13, e14); 80 | val e21 = `+(e2,e3); 81 | val e22 = `-(e2,e3); 82 | val e23 = `*(e2,e3); 83 | val e24 = `/(e2,e3); 84 | val e25 = `*(e7,e4); 85 | eval e15 [] = 5; 86 | eval e16 env1 = 8; 87 | eval e17 env1 = 2; 88 | eval e18 env1 = 15; 89 | eval e19 env1 = 1; 90 | eval e21 env1 = 10; 91 | eval e22 env1 = 6; 92 | eval e23 env1 = 16; 93 | eval e24 env1 = 4; 94 | eval e25 env1 = 150; 95 | 96 | val e30 = Let([Bind("x",Const(3)), Bind("y",`+(Var("x"),Const(1)))] ,`+(Var("x"),Var("y"))); 97 | val e31 = Let([Bind("x",Const(3)), Bind("y",`+(Var("x"),Const(10)))] ,`+(Var("x"),`+(Var("y"),Var("z")))); 98 | val e32 = Let([Bind("x",Const(3)), Bind("y",`~ (Var("x")))] ,Let([Bind("x",Const (100))],`+(Var("x"),Var("y")))); 99 | val e33 = Let([Bind("x",Const(3)), Bind("y",`+ (Var("x"), Const 1))] ,Let([Bind("x",`+(Var "x", Var "y")),Bind("y",`+(Var "x", Var "y"))],`+(Var("x"),Var("y")))); 100 | val e34 = Let([Bind("x",Const(3))], Let([Bind("x",Const (100)), Bind("y", Var "x")],`+(Var("x"),Var("y")))); 101 | val e35 = Let([Bind("x",Const(3))], Let([Bind("x",Const (100)), Bind("y", Var "x")], Let([Bind("x", Const 15),Bind("y", Const 5)],`+(Var("x"),Var("y"))))); 102 | val e36 = Let([Bind("x",Const(3))], Let([Bind("x",Const (100)), Bind("y", Var "x")], Let([Bind("x", Var "x"),Bind("y", Var "y")],`+(Var("x"),Var("y"))))); 103 | 104 | 105 | eval e30 [] = 7; 106 | eval e31 [] = 0 handle UnboundVariable => true; 107 | eval e32 [] = 97; 108 | eval e33 [] = (if type_of_eval = SML then 18 else 14); 109 | eval e34 [] = (if type_of_eval = SML then 200 else 103); 110 | eval e35 [] = (if type_of_eval = SML then 20 else 20); 111 | eval e36 [] = (if type_of_eval = SML then 200 else 103); 112 | -------------------------------------------------------------------------------- /2005_spring/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005_spring/hw1/hw1.pdf -------------------------------------------------------------------------------- /2005_spring/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | 2 | fun ship_size ship = List.length ship 3 | fun shot_hit (sx,sy) = List.exists (fn(x,y)=> x = sx andalso y = sy) 4 | fun ships_collided [] _ = false 5 | | ships_collided (xy::[]) sh2 = shot_hit xy sh2 6 | | ships_collided (xy::xys') sh2 = (shot_hit xy sh2) orelse (ships_collided xys' sh2) 7 | fun biggest_ship [] = 0 8 | | biggest_ship (ship::[]) = ship_size ship 9 | | biggest_ship (ship1::ship2::[]) = if (ship_size ship1) > (ship_size ship2) then (ship_size ship1) else (ship_size ship2) 10 | | biggest_ship (s1::s2::ls') = 11 | let val greatest = biggest_ship (s2::ls') 12 | val size_s1 = ship_size s1 13 | in if size_s1 > greatest then size_s1 else greatest 14 | end 15 | fun salvo_hits [] _ = 0 16 | | salvo_hits _ [] = 0 17 | | salvo_hits (one_shot::[]) (one_ship::[]) = if (shot_hit one_shot one_ship) then 1 else 0 18 | | salvo_hits (shot::salvo) (ls as (one_ship::[])) = (salvo_hits (shot::[]) ls) + (salvo_hits salvo ls) 19 | | salvo_hits (sl as (one_shot::[])) (ship::fleet) = (salvo_hits sl (ship::[])) + (salvo_hits sl fleet) 20 | | salvo_hits (shot::salvo) (fleet as (ship::fleet')) = (salvo_hits (shot::[]) fleet) + (salvo_hits salvo fleet) 21 | 22 | fun valid_damage_reports [] = true 23 | | valid_damage_reports ((size,hits)::[]) = hits <= size 24 | | valid_damage_reports (report::rest) = (valid_damage_reports (report::[])) andalso 25 | (valid_damage_reports rest) 26 | 27 | fun ship_sunk1 [] = [] 28 | | ship_sunk1 ((size,hits)::[]) = if hits = size then [(size,hits)] else [] 29 | | ship_sunk1 (report::rest) = (ship_sunk1 rest)@(ship_sunk1 (report::[])) 30 | 31 | fun ship_sunk [] = NONE 32 | | ship_sunk ((size,hits)::[]) = if hits = size then SOME [(size,hits)] else NONE 33 | | ship_sunk (report::rest) = case ((ship_sunk rest),(ship_sunk (report::[]))) of 34 | (NONE,NONE) => NONE 35 | | (NONE,SOME r) => SOME r 36 | | (SOME r, NONE) => SOME r 37 | | (SOME r, SOME r') => SOME (r@r') 38 | 39 | -------------------------------------------------------------------------------- /2005_spring/hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005_spring/hw2/hw2.pdf -------------------------------------------------------------------------------- /2005_spring/hw2/johnson_hw2.sml: -------------------------------------------------------------------------------- 1 | type grid_ship = (int*int) list 2 | datatype orientation = Horiz | Vert 3 | type ship = { loc : (int*int), dir : orientation, size : int } 4 | type shot_summary = {hits:int, misses:int} 5 | 6 | fun make_horiz 0 = [] 7 | | make_horiz n = (n,0)::(make_horiz (n-1)) 8 | 9 | fun make_vert 0 = [] 10 | | make_vert n = (0,n)::(make_vert (n-1)) 11 | 12 | fun shift ship (c1,c2) = List.map (fn(x,y) => (x+c1,y+c2)) ship 13 | 14 | fun ship_to_grid {loc=loc,dir=dir,size=s} = case dir of 15 | Horiz => shift (make_horiz s) loc 16 | | Vert => shift (make_vert s) loc 17 | fun fleet_to_grid [] = [] 18 | | fleet_to_grid (x::xs') = (fleet_to_grid xs')@(ship_to_grid x) 19 | 20 | fun shot_hit (sx,sy) = List.exists (fn(x,y)=> x = sx andalso y = sy) 21 | 22 | fun fleet_salvo_summary salvo fleet = 23 | let fun {hits=h1,misses=m1} + {hits=h2,misses=m2} = {hits=(h1-(~h2)),misses=(m1-(~m2))} 24 | fun salvo_hits [] _ = {hits=0,misses=0} 25 | | salvo_hits _ [] = {hits=0,misses=0} 26 | | salvo_hits (one_shot::[]) (one_ship::[]) = if (shot_hit one_shot one_ship) 27 | then {hits=1,misses=0} 28 | else {hits=0,misses=1} 29 | | salvo_hits (shot::salvo) (ls as (one_ship::[])) = (salvo_hits (shot::[]) ls) + (salvo_hits salvo ls) 30 | | salvo_hits (sl as (one_shot::[])) (ship::fleet) = (salvo_hits sl (ship::[])) + (salvo_hits sl fleet) 31 | | salvo_hits (shot::salvo) (fleet as (ship::fleet')) = (salvo_hits (shot::[]) fleet) + (salvo_hits salvo fleet) 32 | in salvo_hits salvo fleet 33 | end 34 | 35 | (*SECOND PART - BINARY*) 36 | 37 | datatype bit = One | Zero 38 | type binary_number = bit list 39 | 40 | fun eval_bin bl = 41 | let fun eval [] _ = 0 42 | | eval (bit::bits) c = 43 | case (bit,c > 0) of 44 | (Zero,false) => 0 45 | | (One,false) => 1 46 | | (Zero,true) => eval bits (c-1) 47 | | (One,true) => ceil(Math.pow(2.0,real(c))) + eval bits (c-1) 48 | in eval bl (List.length(bl)-1) 49 | end; 50 | eval_bin [One,Zero,Zero] = 4; 51 | 52 | (*THIRD PART - MEMORY*) 53 | 54 | infix mem 55 | fun x mem [] = false 56 | | x mem (y::ys) = x=y orelse x mem ys 57 | fun newmem(x,xs) = if (x mem xs) then xs else x::xs 58 | 59 | fun setof ls = List.foldl (fn(x,acc)=> newmem(x,acc)) [] ls 60 | 61 | infix union 62 | fun [] union s2 = s2 63 | | s1 union [] = s1 64 | | (s::s1) union s2 = s1 union (newmem(s,s2)); 65 | 66 | 67 | ([1,2,3] union [2,3,4]) = [1,2,3,4]; 68 | 69 | infix isect 70 | fun [] isect s = [] 71 | | s isect [] = [] 72 | | (s::s1) isect s2 = if (s mem s2) 73 | then s::(s1 isect s2) 74 | else (s1 isect s2); 75 | 76 | ([1,2,3] isect [2,3,4]) = [2,3]; 77 | fun one_cross e [] acc = acc 78 | | one_cross e (x::xs') acc = one_cross e xs' (acc@[(e,x)]); 79 | 80 | (one_cross 1 [1,2,3] nil) = [(1,1),(1,2),(1,3)]; 81 | 82 | fun one_cross_noaccum e [] = [] 83 | | one_cross_noaccum e (x::xs') = (one_cross_noaccum e xs')@[(e,x)] 84 | 85 | infix cross 86 | fun [] cross s = [] 87 | | s cross [] = [] 88 | | (s::s1) cross s2 = (s1 cross s2)@(one_cross s s2 []) 89 | -------------------------------------------------------------------------------- /2005_spring/hw3/#johnson_hw3.sml#: -------------------------------------------------------------------------------- 1 | 2 | datatype 'a expr = 3 | Const of bool 4 | | Var of 'a 5 | | Not of 'a expr 6 | | And of 'a expr * 'a expr 7 | | Or of 'a expr * 'a expr 8 | exception UnboundVar 9 | 10 | infix mem 11 | fun x mem [] = false 12 | | x mem (y::ys) = x=y orelse x mem ys 13 | fun newmem(x,xs) = if (x mem xs) then xs else x::xs 14 | 15 | fun setof ls = List.foldl (fn(x,acc)=> newmem(x,acc)) [] ls 16 | 17 | fun free_vars expr = 18 | case expr of 19 | Const _ => [] 20 | | Var x => newmem(x,acc) 21 | | Not e => free_vars e 22 | | And (e1,e2) => (free_vars e1)@(free_vars e2) 23 | | Or (e1,e2) => (free_vars e1)@(free_vars e2) 24 | 25 | -------------------------------------------------------------------------------- /2005_spring/hw3/.#johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | SML@Kevins-MacBook-Pro.local.51949 -------------------------------------------------------------------------------- /2005_spring/hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2005_spring/hw3/hw3.pdf -------------------------------------------------------------------------------- /2005_spring/hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | 2 | datatype 'a expr = 3 | Const of bool 4 | | Var of 'a 5 | | Not of 'a expr 6 | | And of 'a expr * 'a expr 7 | | Or of 'a expr * 'a expr 8 | exception UnboundVar 9 | 10 | infix mem 11 | fun x mem [] = false 12 | | x mem (y::ys) = x=y orelse x mem ys 13 | fun newmem(x,xs) = if (x mem xs) then xs else x::xs 14 | 15 | fun setof ls = List.foldl (fn(x,acc)=> newmem(x,acc)) [] ls 16 | 17 | fun free_vars expr = 18 | let fun helper expr = 19 | case expr of 20 | Const _ => [] 21 | | Var x => [x] 22 | | Not e => helper e 23 | | And (e1,e2) => (helper e1)@(helper e2) 24 | | Or (e1,e2) => (helper e1)@(helper e2) 25 | in setof (helper expr) 26 | end; 27 | free_vars (And(Not(Var "x"),Or(Const true, Var "x"))) = ["x"]; 28 | 29 | fun eval expr = 30 | (*These two helper functions will enforce evaluation of all arguments so that invalid arguments are not shortcircuited from raising exception*) 31 | let fun helperOr e1 e2 = e1 orelse e2 32 | fun helperAnd e1 e2 = e1 andalso e2 33 | in 34 | case expr of 35 | Const b => b 36 | | Var x => raise UnboundVar 37 | | Not e => not (eval e) 38 | | And (e1,e2) => helperAnd (eval e1) (eval e2) 39 | | Or (e1,e2) => helperOr (eval e1) (eval e2) 40 | end; 41 | eval (Or(Const true,Var "x")) handle UnboundVar => true; 42 | 43 | fun bind1 v b e = 44 | case e of 45 | Const bo => Const bo 46 | | Var x => if x = v then Const b else Var x 47 | | Not e => Not (bind1 v b e) 48 | | And (e1,e2) => And (bind1 v b e1, bind1 v b e2) 49 | | Or (e1,e2) => Or (bind1 v b e1, bind1 v b e2); 50 | (bind1 "x" true (And(Var "x",Or(Var "y", Var "x")))) = And(Const true,Or(Var "y", Const true)); 51 | (bind1 "x" true (And(Var "z",Or(Var "y", Var "z")))) = And(Var "z",Or(Var "y", Var "z")); 52 | 53 | fun bind f e = 54 | case e of 55 | Const bo => Const bo 56 | | Var x => f x 57 | | Not e => Not (bind f e) 58 | | And (e1,e2) => And (bind f e1, bind f e2) 59 | | Or (e1,e2) => Or (bind f e1, bind f e2); 60 | 61 | fun bindvar v b e = bind (fn(x)=>if x = v then Const b else Var x) e 62 | fun changevar v b e = bind (fn(x)=> if x = v then Var b else Var x) e; 63 | (bindvar "x" true (And(Var "x",Or(Var "y", Var "x")))) = And(Const true,Or(Var "y", Const true)); 64 | (changevar "x" "help" (And(Var "x",Or(Var "y", Var "x")))) = (And(Var "help",Or(Var "y", Var "help"))); 65 | 66 | fun create_bytes ls = 67 | let val n = List.length ls 68 | val all = ceil(Math.pow(2.0,real(n))) - 1 69 | fun construct_units _ 0 _ = [] 70 | | construct_units (v::vs') n t = 71 | let val size = ceil(Math.pow(2.0,real(n-1))) 72 | fun loop 0 v b = [] 73 | | loop n v b = ((v,b),(bindvar v b))::(loop (n-1) v b) 74 | fun unit v = (loop size v true)@(loop size v false) 75 | fun dupl 0 = [] 76 | | dupl n = (unit v)@(dupl (n-1)) 77 | in [(dupl t)]@(construct_units vs' (n-1) (t*2)) 78 | end 79 | 80 | val units = construct_units ls n 1 81 | fun create_byte i = List.map (fn(l)=>List.nth(l,i)) units 82 | fun loop ~1 = [] 83 | | loop n = (create_byte n)::(loop (n-1)) 84 | in loop all 85 | end 86 | 87 | fun satisfying_assignments e = 88 | let val vars = free_vars e 89 | val size = List.length vars 90 | val bindings = create_bytes vars 91 | fun partial_binding_expr ((b as binding,f),(acc,result)) = (acc@[b],(f result)) 92 | fun apply_bindings ls = 93 | let val (a as applied_binding_summary,c as concrete_expr) = (List.foldl (partial_binding_expr) 94 | ([],e) 95 | ls) 96 | in (a, eval c) 97 | end 98 | val enumeration_results = List.map (fn(ls) => apply_bindings ls) bindings 99 | val relevant_results = List.foldl (fn((a,b),acc)=> if b then acc@[a] else acc) 100 | [] 101 | enumeration_results 102 | in 103 | relevant_results 104 | end; 105 | 106 | 107 | satisfying_assignments (And(Not(Var "x"),Or(Const true, Var "x"))) = [[("x",false)]]; 108 | satisfying_assignments (And(Not(Var "x"),Or(Const false, Var "x"))) = nil; 109 | satisfying_assignments (Or(Var "x", Var "y")) = [ 110 | [("y",false),("x",true)],[("y",true),("x",false)],[("y",true),("x",true)] 111 | ]; 112 | satisfying_assignments (Const true) = [[]]; 113 | satisfying_assignments (Const false) = []; 114 | 115 | (*PART II*) 116 | 117 | datatype atom = AtomConst of string | AtomVar of string 118 | type predicate = { pred : string, vals : atom list }; 119 | exception BadGetBinding 120 | 121 | val state = [ {pred="At", vals=[AtomConst "home"]}, 122 | {pred="Sells",vals=[AtomConst "QFC", AtomConst "Eggs"]} ]; 123 | 124 | (*val buy_precond = And({pred="At", vals=[AtomVar "place"]}, 125 | {pred="Sells", vals=[AtomVar "place",AtomVar "item"]}); 126 | *) 127 | val x = AtomVar "x"; val y = AtomVar "y"; val z = AtomVar "z"; 128 | val QFC = AtomConst "QFC"; val Ace = AtomConst "Ace"; 129 | val Eggs = AtomConst "Eggs"; val Nails = AtomConst "Nails"; 130 | val Home = AtomConst "Home"; val Away = AtomConst "Away"; 131 | val Milk = AtomConst "Milk"; val Ace = AtomConst "Ace"; 132 | fun At(x) = {pred="At", vals=[x]}; 133 | fun Sells(x,y) = {pred="Sells",vals=[x,y]}; 134 | fun Have(x) = {pred="Have", vals=[x]}; 135 | 136 | fun bindatom (x,c) (a as (AtomVar v)) = if x=v then AtomConst c else a 137 | | bindatom _ a = a 138 | 139 | fun bindpred (s as (x,c)) {pred=p,vals=v} = {pred=p,vals=(List.map (fn(a)=>bindatom s a) v)} 140 | fun filter pred [] = [] 141 | | filter pred (l::ls') = if pred l then l::(filter pred ls') else (filter pred ls') 142 | fun getconsts ls = filter (fn(v)=> case v of (AtomConst a) => true | _ => false) ls; 143 | getconsts [QFC,Eggs,Home,Milk,Nails,Away,Ace,x,y,z]; 144 | fun getvars ls = filter (fn(v)=> case v of (AtomVar a) => true | _ => false) ls; 145 | getvars [QFC,Eggs,Home,Milk,Nails,Away,Ace,x,y,z]; 146 | 147 | fun satisfying_matches pred (state as []) = [] 148 | | satisfying_matches (pred as {pred=p,vals=v}) ({pred=q,vals=w}::s') = 149 | let val is_pass_precheck = (p=q) andalso (List.length(v) = List.length(w)) 150 | fun comp_vals (AtomVar _) _ = true 151 | | comp_vals (AtomConst a) (AtomConst b) = a=b 152 | | comp_vals _ _ = false 153 | fun get_value (AtomVar v) = v 154 | | get_value (AtomConst v) = v 155 | fun compare [] [] acc = acc 156 | | compare (v::vs') (w::ws') acc = 157 | if (comp_vals v w) then (compare vs' ws' (acc@[get_value w])) else [] 158 | in if is_pass_precheck 159 | then (compare v w [])::(satisfying_matches pred s') 160 | else (satisfying_matches pred s') 161 | end; 162 | 163 | satisfying_matches {pred="Sells", vals=[AtomVar "x", AtomVar "y"]} 164 | [{pred="Sells", vals=[AtomConst "QFC", AtomConst "Eggs"]}, 165 | {pred="Sells", vals=[AtomConst "Ace", AtomConst "Nails"]}, 166 | {pred="At", vals=[AtomConst "Home"]}, 167 | {pred="Sells", vals=[AtomConst "QFC", AtomConst "Milk"]}]; 168 | satisfying_matches (Sells(x,y)) [At(x),Sells(x,y), At(QFC),Sells(QFC,Eggs)]; 169 | 170 | fun get_binding [] [] = [] 171 | | get_binding (x::xs') [] = raise BadGetBinding 172 | | get_binding [] (y::ys') = raise BadGetBinding 173 | | get_binding (x::xs') (y::ys') = 174 | case (x,y) of 175 | (AtomVar a, AtomConst b) => (a,b)::(get_binding xs' ys') 176 | | (AtomVar a, AtomVar b) => (a,b)::(get_binding xs' ys') 177 | | (AtomConst a, AtomConst b)=> if (a=b) then (get_binding xs' ys') else raise BadGetBinding 178 | | _ => raise BadGetBinding; 179 | 180 | get_binding [AtomVar "x", AtomVar "y"] [QFC,Eggs]; 181 | get_binding [QFC,AtomVar "y"] [QFC,Eggs]; 182 | 183 | fun apply_binding bindings pl = List.map (fn(e)=> (List.foldl (fn(b,acc)=> bindpred b acc) e bindings)) pl 184 | fun bindings_for_one_pred {pred=p,vals=v} s = List.filter List.map (fn({pred=q,vals=w})=> 185 | if (p=q) 186 | then get_binding v w 187 | else []) s; 188 | bindings_for_one_pred (At(Home)) [At(Home)]; 189 | bindings_for_one_pred (At(Home)) [At(Away)] handle BadGetBinding => []; 190 | 191 | fun bindings_for_preds pl s = List.map (fn(p)=> bindings_for_one_pred p s) pl 192 | -------------------------------------------------------------------------------- /2005_spring/hw3/johnson_hw3.sml~: -------------------------------------------------------------------------------- 1 | 2 | datatype ’a expr = 3 | Const of bool 4 | | Var of ’a 5 | | Not of ’a expr 6 | | And of ’a expr * ’a expr 7 | | Or of ’a expr * ’a expr 8 | exception UnboundVar 9 | 10 | infix mem 11 | fun x mem [] = false 12 | | x mem (y::ys) = x=y orelse x mem ys 13 | fun newmem(x,xs) = if (x mem xs) then xs else x::xs 14 | 15 | fun setof ls = List.foldl (fn(x,acc)=> newmem(x,acc)) [] ls 16 | 17 | fun free_vars expr = 18 | case expr of 19 | Const _ => [] 20 | | Var x => newmem(x,acc) 21 | | Not e => free_vars e 22 | | And (e1,e2) => (free_vars e1)@(free_vars e2) 23 | | Or (e1,e2 => (free_vars e1)@(free_vars e2) 24 | 25 | -------------------------------------------------------------------------------- /2006_spring/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2006_spring/hw1/hw1.pdf -------------------------------------------------------------------------------- /2006_spring/hw1/johnson_hw1_tests.sml: -------------------------------------------------------------------------------- 1 | use "johnson_hw1.sml"; 2 | val name_hw = "2006 - Spring - Assignment One: Checkers"; 3 | val p0 = (0,0,1,true) and q0 =(0,0); 4 | val p1 = (1,1,1,false) and q1 = (1,1); 5 | val p2 = (2,2,~1,false) and q2 = (2,2); 6 | val p3 = (1,2,1,false) and q3 = (1,2); 7 | val p4 = (2,1,1,false) and q4 = (2,1); 8 | val p5 = (6,6,2,false) and q5 = (6,6); 9 | val p6 = (3,5,1,false) and q6 = (3,5); 10 | val p7 = (7,7,1,false) and q7 = (7,7); 11 | val p8 = (10,20,1,false) and q8 = (10,20); 12 | val p9 = (~10,0,1,false) and q9 = (~10,0); 13 | 14 | val r0 = (5,3,1,false) and r1 = (1,1,~1,false); 15 | 16 | val c0 = []; 17 | val c1 = [p0]; 18 | val c2 = [p0,p7]; 19 | val c30 = [p7,p0,p2,p1,p6]; 20 | 21 | val c31 = [p1,p7,p0,p2,p1,p6]; (*duplicates*) 22 | val c32 = [p7,p0,p1,p2,p1,p6]; 23 | val c33 = [p7,p0,p2,p1,p6,p1]; 24 | 25 | val c41 = [p3,p7,p0,p2,p1,p6]; (*illegal_piece*) 26 | val c42 = [p7,p0,p2,p3,p1,p6]; 27 | val c43 = [p7,p0,p2,p1,p6,p3]; 28 | 29 | val c51 = [p1,p7,p0,p2,p1,p6,p4]; (*duplicates and illegal_piece*) 30 | val c52 = [p7,p0,p1,p4,p2,p1,p6]; 31 | val c53 = [p4,p7,p0,p2,p1,p6,p1]; 32 | 33 | val c6 = c30 @ c30 @ c30 @ c30 @ c30 @ c30 @ c30 (*Multiple Duplicates*) 34 | 35 | val d as dummy = [((~1,~1,5,true),(~1,~1,5,true),NONE)]; 36 | 37 | fun f1_t p = legal_piece p = true; 38 | fun f1_f p = legal_piece p = false; 39 | fun f2_t c = legal_config c = true; 40 | fun f2_f c = legal_config c = false; 41 | 42 | fun f3_t c p = piece_at c p <>NONE; 43 | fun f3_f c p = piece_at c p = NONE; 44 | 45 | val f4 = legal_move_core; 46 | 47 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 48 | val tests = [ 49 | ("1.00", f1_t p0), 50 | ("1.01", f1_t p1), 51 | ("1.02", f1_t p2), 52 | ("1.03", f1_f p3), 53 | ("1.04", f1_f p4), 54 | ("1.05", f1_f p5), 55 | ("1.06", f1_t p6), 56 | ("1.07", f1_t p7), 57 | ("1.08", f1_f p8), 58 | ("1.09", f1_f p9), 59 | 60 | ("2.00", f2_t c0), 61 | ("2.01", f2_t c1), 62 | ("2.02", f2_t c2), 63 | ("2.03", f2_t c30), 64 | 65 | ("2.10", f2_f c31), 66 | ("2.11", f2_f c32), 67 | ("2.12", f2_f c33), 68 | ("2.20", f2_f c41), 69 | ("2.21", f2_f c42), 70 | ("2.22", f2_f c43), 71 | ("2.30", f2_f c51), 72 | ("2.31", f2_f c52), 73 | ("2.32", f2_f c53), 74 | ("2.40", f2_f c6), 75 | 76 | ("3.00", f3_f c0 q0), (*Test boundaries*) 77 | ("3.01", f3_t c1 q0), 78 | ("3.02", f3_t c2 q0), 79 | ("3.03", f3_t c2 q7), 80 | 81 | ("3.10", f3_t c30 q0), (*Test successful retrievals*) 82 | ("3.11", f3_t c30 q7), 83 | ("3.12", f3_t c30 q2), 84 | ("3.13", f3_t c30 q1), 85 | ("3.14", f3_t c30 q6), 86 | 87 | ("3.20", f3_f c30 q3), (*Test unsuccessful retrievals*) 88 | ("3.21", f3_f c2 q3), 89 | ("3.22", f3_f c1 q3), 90 | ("3.23", f3_f c0 q3), 91 | 92 | (* d is an impossible result so that true can only come about through handling the corresponding exception*) 93 | ("4.00", f4 c31 p0 (1,1) = d handle IllegalConfig => true), 94 | ("4.01", f4 c41 p0 (1,1) = d handle IllegalConfig => true), 95 | ("4.02", f4 c51 p0 (1,1) = d handle IllegalConfig => true), 96 | ("4.03", f4 c6 p0 (1,1) = d handle IllegalConfig => true), 97 | ("4.03", f4 [p8] p8 (1,1) = d handle IllegalConfig => true), 98 | ("4.03", f4 [p9] p9 (1,1) = d handle IllegalConfig => true), 99 | 100 | ("4.10", f4 c1 p0 (1,2) = d handle ImplausibleMove => true), 101 | ("4.11", f4 c1 p0 (2,1) = d handle ImplausibleMove => true), 102 | 103 | ("4.20", f4 [p1] p1 (~1,~1) = d handle IncorrectPlayingDirection => true), 104 | ("4.21", f4 [p1] p1 (1,~1) = d handle IncorrectPlayingDirection => true), 105 | ("4.22", f4 [p2] p2 (1,1) = d handle IncorrectPlayingDirection => true), 106 | ("4.23", f4 [p2] p2 (~1,1) = d handle IncorrectPlayingDirection => true), 107 | 108 | ("4.30", f4 [p7] p7 (1,1) = d handle OutOfBoardRange => true), 109 | ("4.31", f4 [p2] p2 (~3,~3) = d handle OutOfBoardRange => true), 110 | ("4.32", f4 [p2] p2 (3,~3) = d handle OutOfBoardRange => true), 111 | 112 | ("4.40", f4 [p2,p0] p0 (2,2) = d handle DestinationOccupied => true), 113 | 114 | ("4.50", f4 [] p0 (1,1) = d handle PieceNotPresent => true), 115 | ("4.51", f4 [p0] p1 (1,1) = d handle PieceNotPresent => true), 116 | ("4.52", f4 c30 r0 (1,1) = d handle PieceNotPresent => true), 117 | 118 | ("4.60", f4 [p0] p0 (0,0) = d handle ZeroMove => true), 119 | ("4.61", f4 c30 p1 (0,0) = d handle ZeroMove => true), 120 | 121 | ("4.70", f4 [p0,r1,p2] p0 (3,3) = d handle MultiplePiecesInterspersing => true), 122 | 123 | ("4.80", f4 [p0,p1] p0 (2,2) = d handle NotEnemy => true), 124 | 125 | ("4.90", f4 [p1] p1 (5,5) = d handle OnlyOneStep => true), 126 | 127 | ("4.100", f4 [p1,p2] p1 (5,5) = d handle OnlyTwoStepJump => true), 128 | 129 | (*Different legal moves without capture*) 130 | ("5.00", f4 [p0] p0 (1,1) = [(p0,(1,1,1,true),NONE)]), (*Legal moves on part of King*) 131 | ("5.01", f4 [p0] p0 (5,5) = [(p0,(5,5,1,true),NONE)]), 132 | ("5.02", f4 [(5,5,1,true)] (5,5,1,true) (~1,~1) = [((5,5,1,true),(4,4,1,true),NONE)]), 133 | ("5.03", f4 [(5,5,1,true)] (5,5,1,true) (~5,~5) = [((5,5,1,true),(0,0,1,true),NONE)]), 134 | ("5.04", f4 [(5,5,1,true)] (5,5,1,true) (~1,1) = [((5,5,1,true),(4,6,1,true),NONE)]), 135 | ("5.05", f4 [(5,5,1,true)] (5,5,1,true) (1,~1) = [((5,5,1,true),(6,4,1,true),NONE)]), 136 | 137 | ("5.10", f4 [(5,5,1,false)] (5,5,1,false) (~1,1) = [((5,5,1,false),(4,6,1,false),NONE)]), (*Legal Moves on part of Man 1 and ~1 respectively*) 138 | ("5.11", f4 [(5,5,1,false)] (5,5,1,false) (1,1) = [((5,5,1,false),(6,6,1,false),NONE)]), 139 | ("5.12", f4 [(5,5,~1,false)] (5,5,~1,false) (~1,~1) = [((5,5,~1,false),(4,4,~1,false),NONE)]), 140 | ("5.13", f4 [(5,5,~1,false)] (5,5,~1,false) (1,~1) = [((5,5,~1,false),(6,4,~1,false),NONE)]), 141 | 142 | (*Make different captures*) 143 | (*In proximity*) 144 | ("5.20", f4 [(4,4,1,false),(5,5,~1,true)] (4,4,1,false) (2,2) = [((4,4,1,false),(6,6,1,false),SOME (5,5,~1,true))]), 145 | ("5.21", f4 [(4,4,1,true),(5,5,~1,true)] (4,4,1,true) (2,2) = [((4,4,1,true),(6,6,1,true),SOME (5,5,~1,true))]), 146 | 147 | ("5.22", f4 [(4,4,1,false),(5,5,~1,false)] (4,4,1,false) (2,2) = [((4,4,1,false),(6,6,1,false),SOME (5,5,~1,false))]), 148 | ("5.23", f4 [(4,4,1,true),(5,5,~1,false)] (4,4,1,true) (2,2) = [((4,4,1,true),(6,6,1,true),SOME (5,5,~1,false))]), 149 | 150 | ("5.24", f4 [(4,4,1,false),(5,5,~1,true)] (5,5,~1,true) (~2,~2) = [((5,5,~1,true),(3,3,~1,true),SOME (4,4,1,false))]), 151 | ("5.25", f4 [(4,4,1,false),(5,5,~1,false)] (5,5,~1,false) (~2,~2) = [((5,5,~1,false),(3,3,~1,false),SOME (4,4,1,false))]), 152 | 153 | ("5.26", f4 [(4,4,1,true),(5,5,~1,true)] (5,5,~1,true) (~2,~2) = [((5,5,~1,true),(3,3,~1,true),SOME (4,4,1,true))]), 154 | ("5.27", f4 [(4,4,1,true),(5,5,~1,false)] (5,5,~1,false) (~2,~2) = [((5,5,~1,false),(3,3,~1,false),SOME (4,4,1,true))]), 155 | 156 | (*Distant Captures*) 157 | ("5.30", f4 [(1,1,~1,true),(5,5,1,true)] (1,1,~1,true) (5,5) = [((1,1,~1,true),(6,6,~1,true),SOME (5,5,1,true))]), 158 | ("5.31", f4 [(1,1,~1,true),(5,5,1,true)] (5,5,1,true) (~5,~5) = [((5,5,1,true),(0,0,1,true),SOME (1,1,~1,true))]), 159 | 160 | (*Distant Captures with far landing*) 161 | ("5.40", f4 [(1,1,~1,true),(5,5,1,true)] (1,1,~1,true) (6,6) = [((1,1,~1,true),(7,7,~1,true),SOME (5,5,1,true))]), 162 | ("5.41", f4 [(3,3,~1,true),(5,5,1,true)] (5,5,1,true) (~5,~5) = [((5,5,1,true),(0,0,1,true),SOME (3,3,~1,true))]) 163 | 164 | ]; 165 | print ("\n"^Int.toString(List.length(tests))^" TOTAL TESTS RUN----------------------"^name_hw^"--------------------------\n"); (*Name display to assert correct test file is running*) 166 | 167 | fun all_tests(tests) = 168 | let fun helper(tests: (string*bool) list, all_passed) = 169 | case tests of 170 | [] => all_passed 171 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 172 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 173 | in 174 | helper(tests, true) 175 | end; 176 | 177 | case all_tests(tests) of 178 | true => print "--------------EVERY TESTS PASSED-------------\n" 179 | | false => print "--------------SOMETHING IS WRONG-------------------------\n" 180 | -------------------------------------------------------------------------------- /2006_spring/hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2006_spring/hw2/hw2.pdf -------------------------------------------------------------------------------- /2006_winter/hw1/basra_part1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2006_winter/hw1/basra_part1.pdf -------------------------------------------------------------------------------- /2006_winter/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | val Spade = 1; 2 | val Heart = 2; 3 | val Diamond = 3; 4 | val Club = 4; 5 | val Jack = 11; 6 | val Queen = 12; 7 | val King = 13; 8 | 9 | fun isValidHand hand = not (List.exists (fn(s,r)=> s < 1 orelse s > 4 orelse r < 1 orelse r > 13) 10 | hand) 11 | 12 | 13 | fun isValidHand_long [] = true 14 | | isValidHand_long ((s,r)::hs') = s > 0 andalso s < 5 andalso r > 0 andalso r < 14 andalso (isValidHand_long hs') 15 | 16 | fun handHunger h = let val n = List.length(h) in if n < 4 then 4-n else 0 end 17 | 18 | fun handHunger_long h = 19 | let fun count [] = 0 20 | | count (h::hs') = 1 + (count hs') 21 | val n = count h 22 | in if n < 4 then n-4 else 0 23 | end 24 | 25 | fun addToHand c h = let val n = List.length(h) in if n > 5 then [] else c::h end 26 | 27 | fun removeFromHand c [] = [] 28 | | removeFromHand c (h::hs') = if c=h then hs' else h::(removeFromHand c hs') 29 | 30 | fun removeCardsFromHand c [] = [] 31 | | removeCardsFromHand [] h = h 32 | | removeCardsFromHand (c::cs') h = removeCardsFromHand cs' (removeFromHand c h) 33 | 34 | fun earnedScore [] = 0 35 | | earnedScore ((_,r)::hand) = case r of 36 | 11 => 2 + (earnedScore hand) 37 | | 12 => 2 + (earnedScore hand) 38 | | 13 => 2 + (earnedScore hand) 39 | | _ => 1 + (earnedScore hand); 40 | isValidHand([(1, 3), (2, 4)]) = true : bool; 41 | isValidHand([(5, 3), (1, 14)]) = false : bool; 42 | handHunger([(1, 3), (2, 4)]) =2; 43 | handHunger([(1, 3), (2, 4), (4, 11), (2, 1), (1, 13)])=0; 44 | addToHand (1, 3) [(2, 1), (2, 11)] = [(1, 3), (2, 1), (2, 11)]; 45 | addToHand (1, 3) [(3, 3), (2, 4), (4, 11), (2, 1), (1, 13), (3,5)] =[]; 46 | removeFromHand (1, 3) [(1, 11), (2, 4), (1, 3)] = [(1,11),(2,4)]; 47 | removeCardsFromHand [(2, 4), (2, 1)] [(1, 11), (2, 4), (1, 3)] = [(1,11),(1,3)]; 48 | removeCardsFromHand[(2, 4), (2, 1)] [(1, 11), (2, 4), (1, 3)] = [(1,11),(1,3)]; 49 | earnedScore([(1, 3), (1, 11), (2, 13)]) =5; 50 | -------------------------------------------------------------------------------- /2006_winter/hw2/basra_part2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2006_winter/hw2/basra_part2.pdf -------------------------------------------------------------------------------- /2006_winter/hw2/basra_work.sml: -------------------------------------------------------------------------------- 1 | (* datatypes and types and card dealing *) 2 | 3 | datatype suit = Spade | Heart | Diamond | Club 4 | type rank = int; 5 | type card = suit * rank; 6 | type cards = card list; 7 | 8 | fun sort (lst: cards) = ( (* implement your sort function here *) ) 9 | 10 | (* Part 1 of Basra Game *) 11 | 12 | (* 1 - 2 *) 13 | fun handHunger (hand: cards) = if length hand >= 4 then 0 else 4 - length hand; 14 | 15 | (* 1 - 3 *) 16 | fun addToHand (hand: cards, card: card) = if length hand < 6 then card::hand else nil; 17 | 18 | (* extra *) 19 | fun addCardsToHand (hand: cards, cards: cards) = case cards of [] => hand 20 | | head :: tail => addCardsToHand(head :: hand, tail) 21 | (* 1 - 4 *) 22 | fun removeFromHand (hand: cards, card: card) = case hand of [] => [] 23 | | (s: card) :: st => if (card = s) then st else s::removeFromHand(st, card) 24 | 25 | (* 1 - 5 *) 26 | fun removeCardsFromHand (nil, _) = nil 27 | | removeCardsFromHand (hand: cards, nil) = hand 28 | | removeCardsFromHand (hand: cards, (c: card)::cs) = removeCardsFromHand(removeFromHand(hand, c), cs); 29 | 30 | (* 1 - 6 *) 31 | fun earnedScore (nil) = 0 32 | | earnedScore ((s: card)::st) = ( 33 | let 34 | val x = if #2(s) >= 11 then 2 else 1 35 | in 36 | x + earnedScore(st) 37 | end 38 | ); 39 | 40 | (* Part 2 of Basra Game *) 41 | 42 | (* Capture *) 43 | fun capture(floor: cards, card: card) = ( (* implement your capture function here *) ) 44 | 45 | (* Game Over *) 46 | fun isGameOver (deck: cards, floor: cards, hand: cards) = ( (* implement your isGameOver function here *) ) 47 | 48 | (* Helper Function 1 for produceShuffledDeck: Generate a shuffled deck *) 49 | fun produceUnshuffledDeck() = 50 | let 51 | fun generateCardsInSuit(suit: suit, deck: cards, currentRank: int) = 52 | if currentRank > 13 then deck 53 | else generateCardsInSuit(suit, (suit, currentRank) :: deck, currentRank + 1) 54 | val deck1 = generateCardsInSuit(Spade, [], 1) 55 | val deck2 = generateCardsInSuit(Heart, deck1, 1) 56 | val deck3 = generateCardsInSuit(Diamond, deck2, 1) 57 | val deck4 = generateCardsInSuit(Club, deck3, 1) 58 | in 59 | deck4 60 | end 61 | 62 | (* Helper Function 2 for produceShuffledDeck: generates a random integer *) 63 | fun getRandomInt(max: int) = 64 | let 65 | fun Seeder() = let val time = Time.toMilliseconds(Time.now()) 66 | val time' = case Int.maxInt 67 | of NONE => time 68 | | SOME x => LargeInt.mod(time, Int.toLarge x) 69 | in Int.fromLarge time' 70 | end 71 | val RandGen = Random.rand(Seeder(), Seeder()) 72 | in 73 | if max = 0 then NONE 74 | else SOME((Random.randInt(RandGen) mod max) + 1) (* Keep the +1 if you want it to generate from 1 to max, or remove it to generate from 0 to max - 1 *) 75 | end 76 | 77 | (* produceShuffledDeck returns a shuffled deck of 52 distinct cards *) 78 | fun produceShuffledDeck() = ( (* implement your produceShuffledDeck function here *) ) 79 | 80 | -------------------------------------------------------------------------------- /2006_winter/hw2/johnson_hw2.sml: -------------------------------------------------------------------------------- 1 | (* datatypes and types and card dealing *) 2 | 3 | datatype suit = Spade | Heart | Diamond | Club 4 | type rank = int; 5 | type card = suit * rank; 6 | type cards = card list; 7 | 8 | fun sort [] = [] 9 | | sort [c] = [c] 10 | | sort (lst: cards) = 11 | let val ln = length lst 12 | val mid = ln div 2 13 | val p as (ps,pr) = List.nth (lst,mid) 14 | fun isBigger (s1,r1) (s2,r2) = 15 | if s1 = s2 then r1 > r2 else 16 | case (s1,s2) of 17 | (Spade,_) => false 18 | | (Heart,Spade) => true 19 | | (Heart,_) => false 20 | | (Diamond,Spade) => true 21 | | (Diamond,Heart) => true 22 | | (Diamond,_) => false 23 | | (Club,_) => true 24 | val left = List.filter (fn(c as (cs,cr))=> not (cs = ps andalso cr = pr) andalso (not (isBigger c p))) lst 25 | val right = List.filter (fn(c)=> isBigger c p) lst 26 | in 27 | sort(p::left)@(sort(right)) 28 | end 29 | 30 | (* Part 1 of Basra Game *) 31 | 32 | (* 1 - 2 *) 33 | fun handHunger (hand: cards) = if length hand >= 4 then 0 else 4 - length hand; 34 | 35 | (* 1 - 3 *) 36 | fun addToHand (hand: cards, card: card) = if length hand < 6 then card::hand else nil; 37 | 38 | (* extra *) 39 | fun addCardsToHand (hand: cards, cards: cards) = case cards of [] => hand 40 | | head :: tail => addCardsToHand(head :: hand, tail) 41 | (* 1 - 4 *) 42 | fun removeFromHand (hand: cards, card: card) = case hand of [] => [] 43 | | (s: card) :: st => if (card = s) then st else s::removeFromHand(st, card) 44 | 45 | (* 1 - 5 *) 46 | fun removeCardsFromHand (nil, _) = nil 47 | | removeCardsFromHand (hand: cards, nil) = hand 48 | | removeCardsFromHand (hand: cards, (c: card)::cs) = removeCardsFromHand(removeFromHand(hand, c), cs); 49 | 50 | (* 1 - 6 *) 51 | fun earnedScore (nil) = 0 52 | | earnedScore ((s: card)::st) = ( 53 | let 54 | val x = if #2(s) >= 11 then 2 else 1 55 | in 56 | x + earnedScore(st) 57 | end 58 | ); 59 | 60 | (* Part 2 of Basra Game *) 61 | 62 | (* Capture *) 63 | fun produceAllCaptures(floor: cards, card as (cs,cr): card) = 64 | let val summation = List.foldl (fn((_,cr),acc)=> cr+acc) 0 65 | fun combinations [] = [] 66 | | combinations (head::[]) = [[head]] 67 | | combinations (head::neck::tail) = 68 | let fun fold a [] = [] 69 | | fold a (l::ls') = (a@[l],ls')::(fold a ls') 70 | fun enum [] = [] 71 | | enum ((l1,l2)::ls') = l1::(enum(fold l1 l2)) @ enum ls' 72 | in enum [([head],neck::tail)] @ combinations (neck::tail) 73 | end; 74 | in 75 | List.filter (fn(cl)=> summation cl = cr) (combinations floor) 76 | end 77 | 78 | (* Game Over *) 79 | fun isGameOver (deck: cards, floor: cards, hand: cards) = 80 | case (deck,floor,hand) of 81 | ([],[],_) => true 82 | | (_,_,[]) => true 83 | | (_,floor,hand) => List.length (floor) = 6 andalso (List.foldl (fn(c,acc)=> produceAllCaptures(floor,c)@acc) [] hand) = [] 84 | 85 | (* Helper Function 1 for produceShuffledDeck: Generate a shuffled deck *) 86 | fun produceUnshuffledDeck() = 87 | let 88 | fun generateCardsInSuit(suit: suit, deck: cards, currentRank: int) = 89 | if currentRank > 13 then deck 90 | else generateCardsInSuit(suit, (suit, currentRank) :: deck, currentRank + 1) 91 | val deck1 = generateCardsInSuit(Spade, [], 1) 92 | val deck2 = generateCardsInSuit(Heart, deck1, 1) 93 | val deck3 = generateCardsInSuit(Diamond, deck2, 1) 94 | val deck4 = generateCardsInSuit(Club, deck3, 1) 95 | in 96 | deck4 97 | end 98 | 99 | (* Helper Function 2 for produceShuffledDeck: generates a random integer *) 100 | fun getRandomInt(max: int) = 101 | let 102 | fun Seeder() = let val time = Time.toMilliseconds(Time.now()) 103 | val time' = case Int.maxInt 104 | of NONE => time 105 | | SOME x => LargeInt.mod(time, Int.toLarge x) 106 | in Int.fromLarge time' 107 | end 108 | val RandGen = Random.rand(Seeder(), Seeder()) 109 | in 110 | if max = 0 then NONE 111 | else SOME((Random.randInt(RandGen) mod max)) (* Keep the +1 if you want it to generate from 1 to max, or remove it to generate from 0 to max - 1 *) 112 | end 113 | 114 | (* produceShuffledDeck returns a shuffled deck of 52 distinct cards *) 115 | fun produceShuffledDeck() = 116 | let val initial_deck = produceUnshuffledDeck() 117 | fun shuffle deck initial_deck = 118 | let val SOME rnd = getRandomInt(52) 119 | val rnd_card as (s,r) = List.nth(initial_deck,rnd) 120 | val isDuplicate = List.exists (fn(c)=>rnd_card = c) deck 121 | val isComplete = (List.length deck) = 52 122 | in if isComplete then deck else if isDuplicate then shuffle deck initial_deck else shuffle (rnd_card::deck) initial_deck 123 | end 124 | fun loop 0 shuffled = shuffled 125 | | loop n sh = loop (n-1) (shuffle [] sh) 126 | in loop 7 initial_deck 127 | end 128 | 129 | -------------------------------------------------------------------------------- /2006_winter/hw3/.#johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | SML@Kevins-MacBook-Pro.local.86711 -------------------------------------------------------------------------------- /2006_winter/hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2006_winter/hw3/hw3.pdf -------------------------------------------------------------------------------- /2006_winter/hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | fun lreduce f [x] = x 2 | | lreduce f (x::x'::xs') = lreduce f ((f( x, x'))::xs') 3 | 4 | infix \> 5 | fun f1 \> f2 = f2 o f1 6 | fun foldl fl i = 7 | let fun helper [f] = f 8 | | helper (f::fs') = f \> helper fs' 9 | in helper fl i 10 | end 11 | 12 | fun pascal n = 13 | let fun helper 1 _ = [[1]] 14 | | helper 2 _ = [[1,1],[1]] 15 | | helper i (acc as ((head::tail)::rest)) = 16 | let val (current,_) = (List.foldl (fn (e,(acc,prev))=> (acc@[e+prev],e)) ([1],head) tail) 17 | in if i <= n then helper (i+1) ((current@[1])::acc) else acc 18 | end 19 | in List.rev(helper 3 (helper 2 [])) 20 | end; 21 | (* 22 | List.map (fn(l)=> let val p = List.foldl (fn(x,acc)=> acc^" "^(Int.toString(x))) "\n " l in (print p) end ) 23 | (pascal 32);*) 24 | exception BadLists 25 | fun innerproduct l1 l2 = 26 | if length l1 <> length l2 then raise BadLists 27 | else List.foldl (fn((x,y),acc)=> x*y + acc) 0 (ListPair.zip(l1,l2)) 28 | 29 | fun innerproductTail (l::ls') [] _ = raise BadLists 30 | | innerproductTail [] (l::ls') _ = raise BadLists 31 | | innerproductTail [] [] acc = acc 32 | | innerproductTail (x::xs') (y::ys') acc = innerproductTail xs' ys' (x*y+acc) 33 | 34 | fun partition ls g = let fun helper [] pass fail = (pass,fail) 35 | | helper (l::ls') p f = if g l then helper ls' (l::p) f else helper ls' p (l::f) 36 | in helper ls [] [] 37 | end 38 | 39 | fun lessThan p = fn(x)=> x < p 40 | 41 | datatype 'a tree = EmptyT | Tree of 'a * 'a tree * 'a tree 42 | type Tree = int tree 43 | 44 | fun sumTree t = 45 | case t of 46 | EmptyT => 0 47 | | Tree (v,left,right) => v + sumTree left + sumTree right 48 | 49 | fun countNodes t = 50 | case t of 51 | EmptyT => 0 52 | | Tree(v,left,right) => 1 + countNodes left + countNodes right 53 | 54 | 55 | fun findMax t = 56 | let fun helper max t = 57 | case t of 58 | EmptyT => max 59 | | Tree (v, l, r) => let val m1 = helper (if v > max then v else max) l 60 | in helper m1 r 61 | end 62 | in SOME (helper 0 t) 63 | end; 64 | 65 | fun traverse f t = 66 | case t of 67 | EmptyT => f EmptyT 68 | | Tree (v, l, r) => f (Tree (v,l,r)) o traverse f l o traverse f r; 69 | 70 | fun summationT t = (traverse (fn(e)=> 71 | case e of 72 | EmptyT => (fn(x)=>x+0) 73 | | Tree (v,l,r) => (fn(x)=>x+v) 74 | ) t) 0; 75 | 76 | fun countN t = (traverse (fn(e)=> 77 | case e of 78 | EmptyT => (fn(x)=>x+0) 79 | | Tree (v,l,r) => (fn(x)=>x+1) 80 | ) t) 0; 81 | 82 | fun findM t = SOME((traverse (fn(e)=> 83 | case e of 84 | EmptyT => (fn(x)=>x) 85 | | Tree (v,l,r) => (fn(x)=>if x>v then x else v) 86 | ) t) 0); 87 | 88 | val myTree = Tree(5, Tree(4, EmptyT, Tree(7, EmptyT, EmptyT)), Tree(8, Tree(11, EmptyT, EmptyT), EmptyT) ); 89 | sumTree(myTree); 90 | countNodes(myTree); 91 | findMax(myTree); 92 | -------------------------------------------------------------------------------- /2006_winter/hw3/johnson_hw3.sml~: -------------------------------------------------------------------------------- 1 | fun lreduce f [] = [] 2 | | lreduce f [x] = [x] 3 | | lreduce f (x::x'::xs') = (f x x') :: lreduce f ((f x x')::xs') 4 | 5 | -------------------------------------------------------------------------------- /2007_spring/hw1/FAQ - The Rules To the Game of Othello.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2007_spring/hw1/FAQ - The Rules To the Game of Othello.pdf -------------------------------------------------------------------------------- /2007_spring/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2007_spring/hw1/hw1.pdf -------------------------------------------------------------------------------- /2007_spring/hw1/othello-tests.sml: -------------------------------------------------------------------------------- 1 | use "othello.sml"; 2 | val init = (~1,[((4,4),~1),((4,5),1),((5,4),1),((5,5),~1)]); 3 | val hori_l = (~1,[((3,4),~1),((4,4),1),((5,4),1),((6,4),1)]) and hori_l_gap = (7,4) and hori_l_dir = (~1,0); 4 | val hori_r = (~1,[((7,4),~1),((4,4),1),((5,4),1),((6,4),1)]) and hori_r_gap = (3,4) and hori_r_dir = (1,0); 5 | val vert_u = (~1,[((4,8),~1),((4,5),1),((4,6),1),((4,7),1)]) and vert_u_gap = (4,4) and vert_u_dir = (0,1); 6 | val vert_d = (~1,[((4,4),~1),((4,5),1),((4,6),1),((4,7),1)]) and vert_d_gap = (4,8) and vert_d_dir = (0,~1); 7 | val scant1_d = (~1,[((2,2),~1),((3,3),1),((4,4),1),((5,5),1)]) and scant1_d_gap = (6,6) and scant1_d_dir = (~1,~1); 8 | val scant1_u = (~1,[((6,6),~1),((3,3),1),((4,4),1),((5,5),1)]) and scant1_u_gap = (2,2) and scant1_u_dir = (1,1); 9 | val scant2_u = (~1,[((1,8),~1),((2,7),1),((3,6),1),((4,5),1)]) and scant2_u_gap = (5,4) and scant2_u_dir = (~1,1); 10 | val scant2_d = (~1,[((5,4),~1),((2,7),1),((3,6),1),((4,5),1)]) and scant2_d_gap = (1,8) and scant2_d_dir = (1,~1); 11 | 12 | 13 | 14 | val name_hw = "2007 - Spring - Assignment One: Othello" 15 | 16 | val f1 = flanks; 17 | (*Unit tests are of format string*bool where bool is represented by evaluation of a function to an expected value*) 18 | val tests = [ 19 | ("0.01", f1 (0,0) init (1,0) = 1000 handle UnsoundPosition => true), 20 | ("0.02", f1 (9,9) init (1,0) = 1000 handle UnsoundPosition => true), 21 | ("0.03", f1 (1,1) (0,[]) (1,0) = 1000 handle UnsoundState => true), 22 | ("0.04", f1 (1,1) (1,[((1,1),5)]) (1,0) = 1000 handle UnsoundState => true), 23 | ("0.05", f1 (1,1) (1,[((0,1),1)]) (1,0) = 1000 handle UnsoundState => true), 24 | ("0.06", f1 (1,1) (1,[((0,1),~5)]) (1,0) = 1000 handle UnsoundState => true), 25 | ("0.07", f1 (1,1) init (0,0) = 1000 handle UnsoundDirection => true), 26 | ("0.08", f1 (1,1) init (2,1) = 1000 handle UnsoundDirection => true), 27 | 28 | (*check left*) 29 | ("0.10", f1 (3,5) init (1,0) = 1), 30 | ("0.11", f1 (3,5) init (~1,0) = 0), 31 | ("0.12", f1 (3,5) init (0,1) = 0), 32 | ("0.13", f1 (3,5) init (0,~1) = 0), 33 | ("0.14", f1 (3,5) init (1,1) = 0), 34 | ("0.15", f1 (3,5) init (1,~1) = 0), 35 | ("0.16", f1 (3,5) init (~1,1) = 0), 36 | ("0.17", f1 (3,5) init (~1,~1) = 0), 37 | 38 | (*check left top*) 39 | ("0.20", f1 (3,6) init (1,0) = 0), 40 | ("0.21", f1 (3,6) init (~1,0) = 0), 41 | ("0.22", f1 (3,6) init (0,1) = 0), 42 | ("0.23", f1 (3,6) init (0,~1) = 0), 43 | ("0.24", f1 (3,6) init (1,1) = 0), 44 | ("0.25", f1 (3,6) init (1,~1) = 0), 45 | ("0.26", f1 (3,6) init (~1,1) = 0), 46 | ("0.27", f1 (3,6) init (~1,~1) = 0), 47 | 48 | (*check middle-left top*) 49 | ("0.30", f1 (4,6) init (1,0) = 0), 50 | ("0.31", f1 (4,6) init (~1,0) = 0), 51 | ("0.32", f1 (4,6) init (0,1) = 0), 52 | ("0.33", f1 (4,6) init (0,~1) = 1), 53 | ("0.34", f1 (4,6) init (1,1) = 0), 54 | ("0.35", f1 (4,6) init (1,~1) = 0), 55 | ("0.36", f1 (4,6) init (~1,1) = 0), 56 | ("0.37", f1 (4,6) init (~1,~1) = 0), 57 | 58 | (*check middle-right top*) 59 | ("0.40", f1 (5,6) init (1,0) = 0), 60 | ("0.41", f1 (5,6) init (~1,0) = 0), 61 | ("0.42", f1 (5,6) init (0,1) = 0), 62 | ("0.43", f1 (5,6) init (0,~1) = 0), 63 | ("0.44", f1 (5,6) init (1,1) = 0), 64 | ("0.45", f1 (5,6) init (1,~1) = 0), 65 | ("0.46", f1 (5,6) init (~1,1) = 0), 66 | ("0.47", f1 (5,6) init (~1,~1) = 0), 67 | 68 | (*check right top*) 69 | ("0.50", f1 (6,6) init (1,0) = 0), 70 | ("0.51", f1 (6,6) init (~1,0) = 0), 71 | ("0.52", f1 (6,6) init (0,1) = 0), 72 | ("0.53", f1 (6,6) init (0,~1) = 0), 73 | ("0.54", f1 (6,6) init (1,1) = 0), 74 | ("0.55", f1 (6,6) init (1,~1) = 0), 75 | ("0.56", f1 (6,6) init (~1,1) = 0), 76 | ("0.57", f1 (6,6) init (~1,~1) = 0), 77 | 78 | (*check right*) 79 | ("0.60", f1 (6,5) init (1,0) = 0), 80 | ("0.61", f1 (6,5) init (~1,0) = 0), 81 | ("0.62", f1 (6,5) init (0,1) = 0), 82 | ("0.63", f1 (6,5) init (0,~1) = 0), 83 | ("0.64", f1 (6,5) init (1,1) = 0), 84 | ("0.65", f1 (6,5) init (1,~1) = 0), 85 | ("0.66", f1 (6,5) init (~1,1) = 0), 86 | ("0.67", f1 (6,5) init (~1,~1) = 0), 87 | 88 | (*check right*) 89 | ("0.70", f1 (6,4) init (1,0) = 0), 90 | ("0.71", f1 (6,4) init (~1,0) = 1), 91 | ("0.72", f1 (6,4) init (0,1) = 0), 92 | ("0.73", f1 (6,4) init (0,~1) = 0), 93 | ("0.74", f1 (6,4) init (1,1) = 0), 94 | ("0.75", f1 (6,4) init (1,~1) = 0), 95 | ("0.76", f1 (6,4) init (~1,1) = 0), 96 | ("0.77", f1 (6,4) init (~1,~1) = 0), 97 | 98 | (*check right bottom*) 99 | ("0.80", f1 (6,3) init (1,0) = 0), 100 | ("0.81", f1 (6,3) init (~1,0) = 0), 101 | ("0.82", f1 (6,3) init (0,1) = 0), 102 | ("0.83", f1 (6,3) init (0,~1) = 0), 103 | ("0.84", f1 (6,3) init (1,1) = 0), 104 | ("0.85", f1 (6,3) init (1,~1) = 0), 105 | ("0.86", f1 (6,3) init (~1,1) = 0), 106 | ("0.87", f1 (6,3) init (~1,~1) = 0), 107 | 108 | (*check middle bottom*) 109 | ("0.90", f1 (5,3) init (1,0) = 0), 110 | ("0.91", f1 (5,3) init (~1,0) = 0), 111 | ("0.92", f1 (5,3) init (0,1) = 1), 112 | ("0.93", f1 (5,3) init (0,~1) = 0), 113 | ("0.94", f1 (5,3) init (1,1) = 0), 114 | ("0.95", f1 (5,3) init (1,~1) = 0), 115 | ("0.96", f1 (5,3) init (~1,1) = 0), 116 | ("0.97", f1 (5,3) init (~1,~1) = 0), 117 | 118 | (*check middle bottom to left*) 119 | ("0.100", f1 (4,3) init (1,0) = 0), 120 | ("0.101", f1 (4,3) init (~1,0) = 0), 121 | ("0.102", f1 (4,3) init (0,1) = 0), 122 | ("0.103", f1 (4,3) init (0,~1) = 0), 123 | ("0.104", f1 (4,3) init (1,1) = 0), 124 | ("0.105", f1 (4,3) init (1,~1) = 0), 125 | ("0.106", f1 (4,3) init (~1,1) = 0), 126 | ("0.107", f1 (4,3) init (~1,~1) = 0), 127 | 128 | (*check left bottom bottom*) 129 | ("0.110", f1 (3,3) init (1,0) = 0), 130 | ("0.111", f1 (3,3) init (~1,0) = 0), 131 | ("0.112", f1 (3,3) init (0,1) = 0), 132 | ("0.113", f1 (3,3) init (0,~1) = 0), 133 | ("0.114", f1 (3,3) init (1,1) = 0), 134 | ("0.115", f1 (3,3) init (1,~1) = 0), 135 | ("0.116", f1 (3,3) init (~1,1) = 0), 136 | ("0.117", f1 (3,3) init (~1,~1) = 0), 137 | 138 | (*check left bottom*) 139 | ("0.120", f1 (3,4) init (1,0) = 0), 140 | ("0.121", f1 (3,4) init (~1,0) = 0), 141 | ("0.122", f1 (3,4) init (0,1) = 0), 142 | ("0.123", f1 (3,4) init (0,~1) = 0), 143 | ("0.124", f1 (3,4) init (1,1) = 0), 144 | ("0.125", f1 (3,4) init (1,~1) = 0), 145 | ("0.126", f1 (3,4) init (~1,1) = 0), 146 | ("0.127", f1 (3,4) init (~1,~1) = 0), 147 | 148 | ("1.00", f1 hori_l_gap hori_l hori_l_dir = 3), 149 | ("1.01", f1 hori_r_gap hori_r hori_r_dir = 3), 150 | ("1.02", f1 vert_u_gap vert_u vert_u_dir = 3), 151 | ("1.03", f1 vert_d_gap vert_d vert_d_dir = 3), 152 | ("1.04", f1 scant1_d_gap scant1_d scant1_d_dir = 3), 153 | ("1.05", f1 scant1_u_gap scant1_u scant1_u_dir = 3), 154 | ("1.06", f1 scant2_u_gap scant2_u scant2_u_dir = 3), 155 | ("1.07", f1 scant2_d_gap scant2_d scant2_d_dir = 3) 156 | ]; 157 | 158 | print ("\n"^Int.toString(List.length(tests))^" TOTAL TESTS RUN----------------------"^name_hw^"--------------------------\n"); (*Name display to assert correct test file is running*) 159 | fun all_tests(tests) = 160 | let fun helper(tests: (string*bool) list, all_passed) = 161 | case tests of 162 | [] => all_passed 163 | | (st, true)::rest => helper(rest, all_passed) (*I am only interested in the output if the test fails.*) 164 | | (st, false)::rest => (print ("***" ^ st ^" !!!FAILED!!!\n"); helper(rest, false)) 165 | in 166 | helper(tests, true) 167 | end; 168 | 169 | case all_tests(tests) of 170 | true => print "--------------EVERY TESTS PASSED-------------\n" 171 | | false => print "--------------SOMETHING IS WRONG-------------------------\n"; 172 | 173 | val next1 = move (3,5) init; show next1; 174 | val next2 = move (3,6) next1; show next2; 175 | val next3 = move (5,3) next2; show next3; 176 | val next4 = move (4,3) next3; show next4; 177 | val next5 = move (3,3) next4; show next5; 178 | val next6 = move (4,2) next5; show next6; 179 | val next7 = move (2,7) next6; show next7; 180 | val next8 = move (6,4) next7; show next8; 181 | val next9 = move (6,3) next8; show next9; 182 | -------------------------------------------------------------------------------- /2007_spring/hw1/othello.sml: -------------------------------------------------------------------------------- 1 | fun legalpos (x,y) = x>0 andalso x <9 andalso y>0 andalso y<9 2 | fun color (pos as (x,y)) (state as (turn, [])) = 0 3 | | color (pos as (x,y)) (state as (turn, (piece_coord,c)::board)) = if piece_coord = pos then if legalpos pos then c else 0 else color pos (turn, board) 4 | fun color2 (pos as (x,y)) (state as (turn, board)) = case List.find (fn(coord,_)=>pos=coord) board of 5 | NONE => 0 6 | | SOME (coord,c) => if legalpos coord then c else 0 7 | fun emptysquare pos state = color pos state = 0 8 | fun is_sound_state (t,lst) = (t=1 orelse t= ~1) andalso List.foldl (fn((coord,col),acc) => (col= ~1 orelse col=1) andalso legalpos coord andalso acc) true lst 9 | val sound_directions = [(1,0),(~1,0),(0,1),(0,~1),(1,1),(1,~1),(~1,1),(~1,~1)]; 10 | fun is_sound_direction d = List.exists (fn(d')=> d=d') sound_directions 11 | 12 | fun show_piece ((x,y),c) = 13 | let val prepend = if x=1 then "\n "^Int.toString(y) ^" " else " " 14 | in prepend ^ (case c of 15 | ~1 => "*" 16 | | 0 => "." 17 | | 1 => "o") 18 | end 19 | 20 | fun p2Str ((x,y),c) = show_piece ((5,5),c)^" ("^Int.toString(x)^","^Int.toString(y)^")" 21 | fun s2Str (t,lst) = "to move: "^show_piece ((5,5),t)^" "^ List.foldl (fn(p,acc)=> acc^ p2Str p ^ " ") "" lst 22 | 23 | exception UnsoundState and UnsoundDirection and UnsoundPosition 24 | fun retrieve_converts (pos as (px,py)) (state as (t,brd)) (dir as (dx,dy)) = 25 | let val assert_sound_state = if is_sound_state state then true else raise UnsoundState 26 | val assert_sound_direction = if is_sound_direction dir then true else raise UnsoundDirection 27 | val assert_sound_position = if legalpos pos then true else raise UnsoundPosition 28 | fun count (pos as (x,y)) acc = 29 | let val piece = List.find (fn(coord,c)=> pos=coord) brd 30 | val (is_stop,is_count) = case piece of 31 | NONE => (true,false) 32 | | SOME (coord,c) => (c=t,true) 33 | val _ = ("\n"^ p2Str ((x,y),color (x,y) state)) (*for debugging purposes print out*) 34 | in if is_stop then if is_count then acc else [] else count (x+dx,y+dy) (pos :: acc) 35 | end 36 | in count (px+dx,py+dy) [] 37 | end 38 | 39 | fun flanks p s d = length (retrieve_converts p s d) 40 | 41 | fun move (p as (px,py)) (s as (t,brd)) = 42 | let val assert_sound_state = if is_sound_state s then true else raise UnsoundState 43 | val assert_sound_position = if legalpos p then true else raise UnsoundPosition 44 | val all_converts = List.concat (List.map (fn(d)=> retrieve_converts p s d) sound_directions) 45 | val (pass,fail) = List.partition (fn(co,_)=> List.exists (fn(co')=> co=co') all_converts) brd 46 | val change_them = List.map (fn(co,col)=> (co,t)) pass 47 | val new_board = (p,t) :: change_them @ fail 48 | in (~t,new_board) 49 | end 50 | 51 | 52 | fun show (s as (t,brd)) = 53 | let fun loop 8 1 = show_piece ((8,1),color (8,1) s)^"\n" 54 | | loop 8 y = show_piece ((8,y),color (8,y) s)^loop 1 (y-1) 55 | | loop x y = show_piece ((x,y),color (x,y) s)^loop (x+1) y 56 | val msg = "\n"^ show_piece((5,5),t)^" to move; board:" 57 | in print (msg^ loop 1 8) 58 | end 59 | -------------------------------------------------------------------------------- /2007_spring/hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2007_spring/hw2/hw2.pdf -------------------------------------------------------------------------------- /2007_spring/hw2/hw2.sml: -------------------------------------------------------------------------------- 1 | Control.Print.printDepth := 99; (* deep structs for debugging. yes, := *) 2 | infix mem 3 | fun x mem [] = false 4 | | x mem (y::ys) = x=y orelse x mem ys 5 | fun addmem x xs = if (x mem xs) then xs else x::xs 6 | fun remmem x xs = List.foldl (fn(y,acc)=> if y=x then acc else y::acc) [] xs 7 | fun setof xs = List.foldl (fn(x,acc)=>addmem x acc) [] xs 8 | infix union 9 | fun xs union ys = List.foldl (fn(x,acc)=> addmem x acc) (setof ys) xs 10 | fun isect_1 [] ys = [] 11 | | isect_1 xs [] = [] 12 | | isect_1 (x::xs') ys = if x mem ys then x :: isect_1 xs' ys else isect_1 xs' ys 13 | 14 | fun isect2 xs ys = 15 | let fun helper [] ys acc = acc 16 | | helper xs [] acc = acc 17 | | helper (x::xs') ys acc = if x mem ys then helper xs' ys (x::acc) else helper xs' ys acc 18 | in helper xs ys [] 19 | end 20 | 21 | fun isect_foldl xs ys = List.foldl (fn(x,acc) => if x mem ys then x::acc else acc) [] xs 22 | fun isect_filter xs ys = List.filter (fn(x)=> x mem ys) xs 23 | 24 | val t1 = isect_1 [1,2,3] [2,3,4]; 25 | val t2 = isect2 [1,2,3] [2,3,4]; 26 | val t3 = isect_foldl [1,2,3] [2,3,4]; 27 | val t4 = isect_filter [1,2,3] [2,3,4]; 28 | 29 | datatype expr = Const of bool 30 | | Var of string 31 | | Not of expr 32 | | And of expr * expr 33 | | Or of expr * expr 34 | | All of string * expr 35 | | Exist of string * expr 36 | 37 | exception UnboundVar 38 | 39 | val T = Const true; 40 | val F = Const false; 41 | val x = Var "x"; 42 | val y = Var "y"; 43 | val z = Var "z"; 44 | 45 | fun free_vars e = 46 | let fun helper (Const _) = [] 47 | | helper (Var v) = [v] 48 | | helper (Not e) = helper e 49 | | helper (And (e1,e2)) = helper e1 @ helper e2 50 | | helper (Or (e1,e2)) = helper e1 @ helper e2 51 | | helper (All (_,e)) = helper e 52 | | helper (Exist (_,e)) = helper e 53 | in setof (helper e) 54 | end 55 | 56 | fun getenv x env = case List.find (fn(s,v)=> s=x) env of 57 | NONE => raise UnboundVar 58 | | SOME (s,v) => v 59 | 60 | fun eval e env = case e of 61 | Const b => b 62 | | Var x => getenv x env 63 | | Not e => not (eval e env) 64 | | And (e1,e2) => (fn(t1,t2)=>t1 andalso t2)(eval e1 env,eval e2 env) 65 | | Or (e1,e2) => (fn(t1,t2)=>t1 orelse t2)(eval e1 env,eval e2 env) 66 | | All (x,e) => eval e ((x,true)::env) andalso eval e ((x,false)::env) 67 | | Exist (x,e) => eval e ((x,true)::env) orelse eval e ((x,false)::env) 68 | 69 | fun fix1 x b e = case e of 70 | Const b => Const b 71 | | Var y => if y=x then Const b else Var y 72 | | Not e => Not (fix1 x b e) 73 | | And (e1,e2) => And (fix1 x b e1,fix1 x b e2) 74 | | Or (e1,e2) => Or (fix1 x b e1, fix1 x b e2) 75 | | All (s,e) => All (s,e) 76 | | Exist (s,e) => Exist (s,e) 77 | 78 | fun fix f e = 79 | let fun helper e a = 80 | case e of 81 | Const b => Const b 82 | | Var y => if a=NONE orelse (SOME y)<>a then f (Var y) else Var y 83 | | Not e => Not (helper e a) 84 | | And (e1,e2) => And (helper e1 a, helper e2 a) 85 | | Or (e1,e2) => Or (helper e1 a, helper e2 a) 86 | | All (s,e) => All (s, helper e (SOME s)) 87 | | Exist (s,e) => Exist (s, helper e (SOME s)) 88 | in helper e NONE 89 | end 90 | 91 | fun fixvar s b e = fix (fn(Var x)=> if x=s then Const b else Var x) e 92 | fun changevar s v e = fix (fn(Var x)=> if x=s then Var v else Var x) e 93 | fun swapvar x y e = fix (fn(Var l)=> if l=x then Var y else if l=y then Var x else Var l) e 94 | 95 | fun satisfying_assignments e = 96 | let fun helper [] env e = 97 | let val fvs = free_vars e 98 | val en = if fvs = [] then env else List.filter (fn(x,_)=> List.exists (fn(y)=>x<>y) fvs) env 99 | in if eval e [] then [en] else [] 100 | end 101 | | helper (fv::fvs) env e = helper fvs ((fv,true)::env) (fixvar fv true e) @ helper fvs ((fv,false)::env) (fixvar fv false e) 102 | in setof (helper (free_vars e) [] e) 103 | end 104 | 105 | val t5 = free_vars (And(x,All("x",Or(x,Exist("y",Or(x,Or(y,Exist("x",Or(Not(x),z))))))))); 106 | val t6 = getenv "z" [("x",true),("z",false),("z",true)] = false; 107 | val t7 = eval (Or(Const true,Var "x")) [("x",true),("z",false),("z",true)] = true; 108 | val t8 = eval (Or((Var "x"),Const false)) [("x",true),("z",false),("z",true)] = true; 109 | val t9 = eval (Or(Const true,Var "x")) [("z",false),("z",true)] = false handle UnboundVar => true; 110 | val t10 = eval (Or((Var "x"),Const true)) [("z",false),("z",true)] = false handle UnboundVar => true; 111 | val t11 = fix1 "x" true (And(Var "x", Or(All("x", Var "x"), Var "x"))); 112 | val t12 = fix1 "x" true (And(Var "z", Or(Var "y", Var "z"))); 113 | val t13 = fixvar "x" true (And(Var "x",Or(All("x",And(Var "x",Var "y")), Var "x"))); 114 | val t14 = changevar "x" "help" (And(Var "x",Or(All("x",And(Var "x",Var "y")), Var "x"))); 115 | val t15 = swapvar "x" "y" (And(Var "x",Or(Var "x",Var "y"))); 116 | val t16 = swapvar "x" "y" (And(Var "y",Or(All("x",And(Var "x",Var "y")), Var "y"))); (*Results in only one free variable*) 117 | val t17 = satisfying_assignments (And(Not(Var "x"),Or(Const true, Var "x"))); 118 | val t18 = satisfying_assignments (And(Not(Var "x"),Or(Const false, Var "x"))); 119 | val t19 = satisfying_assignments (Or(Var "x", Var "y")); 120 | val t20 = satisfying_assignments (And(Not(Var "x"),Exist("y",Or(Var "y",Var "x")))); 121 | -------------------------------------------------------------------------------- /2007_spring/hw2/hw2.sml~: -------------------------------------------------------------------------------- 1 | Control.Print.printDepth := 99; (* deep structs for debugging. yes, := *) 2 | infix mem 3 | fun x mem [] = false 4 | | x mem (y::ys) = x=y orelse x mem ys 5 | fun addmem x xs = if (x mem xs) then xs else x::xs 6 | 7 | -------------------------------------------------------------------------------- /2007_winter/hw1/.#johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | SML@Kevins-MacBook-Pro.local.86711 -------------------------------------------------------------------------------- /2007_winter/hw1/CSE341, Winter 2007.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2007_winter/hw1/CSE341, Winter 2007.pdf -------------------------------------------------------------------------------- /2007_winter/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | fun pow x 0 = "1" 2 | | pow x y = 3 | let fun pos_pow 0 = 1 4 | | pos_pow y = x * (pos_pow (y-1)) 5 | fun neg_pow 0 = 1.0 6 | | neg_pow y = (1.0/real(x)) * (neg_pow (y+1)) 7 | in if y>0 then Int.toString(pos_pow y) else Real.toString(neg_pow y) 8 | end 9 | 10 | fun sumTo 0 = 0.0 11 | | sumTo n = 1.0/real(n) + sumTo (n-1) 12 | 13 | fun repeat s 0 = "" 14 | | repeat s n = if n < 0 then "" else s ^ repeat s (n-1) 15 | 16 | fun twos 0 = 0 17 | | twos i = if i mod 2 = 0 then 1 + twos (i div 2) else 0 18 | 19 | fun range s e = if s <= e then s :: range (s+1) e else [] 20 | 21 | fun numNegative [] = 0 22 | | numNegative (l::ls') = if l < 0 then 1 + numNegative ls' else numNegative ls' 23 | 24 | fun absList [] = [] 25 | | absList ((x,y)::ls') = (abs x, abs y) :: absList ls' 26 | 27 | fun isSorted [] = true 28 | | isSorted [x] = true 29 | | isSorted (x::x'::xs') = x < x' andalso isSorted (x'::xs') 30 | 31 | fun isSorted2 l = if l = [] then true 32 | else if length l = 1 then true 33 | else (hd l) < (hd (tl l)) andalso isSorted2 (tl l) 34 | 35 | fun collapse [] = [] 36 | | collapse [x] = [x] 37 | | collapse (x::x'::xs') = (x+x') :: collapse xs' 38 | 39 | fun collapse2 l = #1 (List.foldr (fn(x,(acc,prev,track))=> if track 40 | then ((x+prev)::acc,0,false) 41 | else (acc,x,true)) 42 | ([],0,length l mod 2 <> 0) 43 | l) 44 | (*Challenge criteria met: O(n^0.5) time *) 45 | fun factors i = 46 | let fun helper n acc = 47 | if n = 0 then acc else 48 | if i mod n = 0 then helper (n - 1) (n::acc) else helper (n - 1) acc 49 | in helper (i div 2) [i] 50 | end 51 | -------------------------------------------------------------------------------- /2013/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/.DS_Store -------------------------------------------------------------------------------- /2013/hw1/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw1/.DS_Store -------------------------------------------------------------------------------- /2013/hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw1/hw1.pdf -------------------------------------------------------------------------------- /2013/hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | fun is_older(d1: int*int*int, d2: int*int*int) = 2 | if (#1 d1) < (#1 d2) 3 | then true 4 | else if (#1 d1) = (#1 d2) andalso (#2 d1) < (#2 d2) 5 | then true 6 | else if (#2 d1) = (#2 d2) andalso (#3 d1) < (#3 d2) 7 | then true 8 | else false 9 | 10 | fun number_in_month(ld: (int*int*int) list, m: int) = 11 | if null ld 12 | then 0 13 | else if #2 (hd ld) = m 14 | then 1 + number_in_month(tl ld, m) 15 | else number_in_month(tl ld, m) 16 | 17 | fun number_in_months(ld: (int*int*int) list, lm: int list) = 18 | if null lm 19 | then 0 20 | else number_in_month(ld, hd lm) + number_in_months(ld, tl lm) 21 | 22 | fun dates_in_month(ld: (int*int*int) list, m: int) = 23 | if null ld 24 | then [] 25 | else let val md = (hd ld) 26 | in if #2 md = m 27 | then md::dates_in_month(tl ld, m) 28 | else dates_in_month(tl ld, m) 29 | end 30 | 31 | fun dates_in_months(ld: (int*int*int) list, lm: int list) = 32 | if null lm 33 | then [] 34 | else dates_in_month(ld, hd lm) @ dates_in_months(ld, tl lm) 35 | 36 | fun get_nth(ls: string list, n: int) = 37 | if n = 1 38 | then hd ls 39 | else get_nth(tl ls, n - 1) 40 | 41 | fun date_to_string(d: int*int*int) = 42 | let val months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 43 | val year = Int.toString(#1 d) 44 | val month = #2 d 45 | val day = " " ^ Int.toString(#3 d) ^ ", " 46 | in get_nth(months, month) ^ day ^ year 47 | end 48 | 49 | fun number_before_reaching_sum(sum: int, l: int list) = 50 | let fun summation(s: int, c: int, l: int list) = 51 | if s >= sum 52 | then c 53 | else summation(s + hd l, c + 1, tl l) 54 | in summation(0, ~1, l) 55 | end 56 | 57 | fun what_month(d: int) = 58 | let val months = [31,28,31,30,31,30,31,31,30,31,30,31] 59 | in number_before_reaching_sum(d, months) + 1 60 | end 61 | 62 | fun month_range(day1: int, day2: int) = 63 | if day1 > day2 64 | then [] 65 | else let fun range(from: int, to: int) = 66 | if from = to 67 | then [to] 68 | else from::range(from + 1, to) 69 | in range(what_month(day1), what_month(day2)) 70 | end 71 | 72 | fun oldest(l: (int*int*int) list) = 73 | if null l 74 | then NONE 75 | else let val max = oldest(tl l) 76 | in if max = NONE 77 | then SOME (hd l) 78 | else if is_older(hd l, valOf max) 79 | then SOME (hd l) 80 | else max 81 | end 82 | 83 | fun oldest_test(l: int list) = 84 | if null l 85 | then NONE 86 | else let val max = oldest_test(tl l) 87 | in if max = NONE 88 | then SOME (hd l) 89 | else if hd l < valOf max 90 | then SOME (hd l) 91 | else max 92 | end; 93 | 94 | fun remove_duplicates(l: int list) = 95 | let fun find(el: int, l: int list) = 96 | if null l 97 | then false 98 | else if el = hd l 99 | then true 100 | else find(el, tl l) 101 | in 102 | if null l 103 | then [] 104 | else if find(hd l, tl l) 105 | then remove_duplicates(tl l) 106 | else (hd l)::remove_duplicates(tl l) 107 | end 108 | 109 | fun number_in_months_challenge(ld: (int*int*int) list, lm: int list) = 110 | number_in_months(ld, remove_duplicates(lm)) 111 | 112 | fun dates_in_months_challenge(ld: (int*int*int) list, lm: int list) = 113 | dates_in_months(ld, remove_duplicates(lm)) 114 | 115 | fun reasonable_date(d: int*int*int) = 116 | let 117 | val year = #1 d 118 | val month = #2 d 119 | val day = #3 d 120 | val is_leapyear = year mod 400 = 0 orelse (year mod 4 = 0 andalso year mod 100 <> 0) 121 | val is_reasonable_year = year > 0 122 | val is_reasonable_month = month > 0 andalso month < 13 123 | val get_months = 124 | if is_leapyear 125 | then [31,29,31,30,31,30,31,31,30,31,30,31] 126 | else [31,28,31,30,31,30,31,31,30,31,30,31] 127 | fun get_max_days_of_month(ml: int list, m: int) = 128 | if m = 1 orelse not is_reasonable_month (*important bug fix. if invalid months are inputted then uncaught exception even though get_max_days_of_month should not get evaluated as it should get short circuited at failure of is_reasonable_month conjunction*) 129 | then hd ml 130 | else get_max_days_of_month(tl ml, m - 1) 131 | val is_reasonable_day = day > 0 andalso day <= get_max_days_of_month(get_months, month)) 132 | in is_reasonable_year andalso is_reasonable_month andalso is_reasonable_day 133 | end; 134 | 135 | use "johnson_hw1_test.sml"; 136 | -------------------------------------------------------------------------------- /2013/hw1/johnson_hw1.sml~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw1/johnson_hw1.sml~ -------------------------------------------------------------------------------- /2013/hw1/johnson_hw1_test.sml~: -------------------------------------------------------------------------------- 1 | use "johnson_hw1.sml" 2 | 3 | val d1 = (1981,7,5) 4 | val d2 = (1982,1,1) 5 | val d3 = (1981,6,15) 6 | val d4 = (1981,8,1) 7 | val d5 = (1981,7,1) 8 | val d6 = (1981,7,15) 9 | val d7 = (1981,~7,5) 10 | val d8 = (~1982,7,5) 11 | 12 | val test_is_older = is_older(d1,d2) 13 | -------------------------------------------------------------------------------- /2013/hw1/unit1notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw1/unit1notes.pdf -------------------------------------------------------------------------------- /2013/hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw2/hw2.pdf -------------------------------------------------------------------------------- /2013/hw2/hw2provided.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | 11 | (* you may assume that Num is always used with values 2, 3, ..., 10 12 | though it will not really come up *) 13 | datatype suit = Clubs | Diamonds | Hearts | Spades 14 | datatype rank = Jack | Queen | King | Ace | Num of int 15 | type card = suit * rank 16 | 17 | datatype color = Red | Black 18 | datatype move = Discard of card | Draw 19 | 20 | exception IllegalMove 21 | 22 | (* put your solutions for problem 2 here *) 23 | fg 24 | -------------------------------------------------------------------------------- /2013/hw2/hw2provided.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | 11 | (* you may assume that Num is always used with values 2, 3, ..., 10 12 | though it will not really come up *) 13 | datatype suit = Clubs | Diamonds | Hearts | Spades 14 | datatype rank = Jack | Queen | King | Ace | Num of int 15 | type card = suit * rank 16 | 17 | datatype color = Red | Black 18 | datatype move = Discard of card | Draw 19 | 20 | exception IllegalMove 21 | 22 | (* put your solutions for problem 2 here *) 23 | -------------------------------------------------------------------------------- /2013/hw2/hw2providedTests.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Tests *) 2 | 3 | (* These are just two tests for problem 2; you will want more. 4 | 5 | Naturally these tests and your tests will use bindings defined 6 | in your solution, in particular the officiate function, 7 | so they will not type-check if officiate is not defined. 8 | *) 9 | 10 | fun provided_test1 () = (* correct behavior: raise IllegalMove *) 11 | let val cards = [(Clubs,Jack),(Spades,Num(8))] 12 | val moves = [Draw,Discard(Hearts,Jack)] 13 | in 14 | officiate(cards,moves,42) 15 | end 16 | 17 | fun provided_test2 () = (* correct behavior: return 3 *) 18 | let val cards = [(Clubs,Ace),(Spades,Ace),(Clubs,Ace),(Spades,Ace)] 19 | val moves = [Draw,Draw,Draw,Draw,Draw] 20 | in 21 | officiate(cards,moves,42) 22 | end 23 | -------------------------------------------------------------------------------- /2013/hw2/johnson_hw2.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | fun all_except_option(s, sl) = 11 | let fun helper(l) = 12 | case l of 13 | [] => [] 14 | | x::xs' => if same_string(s,x) then helper(xs') else x::helper(xs') 15 | in 16 | case sl of 17 | [] => NONE 18 | | _ => if helper(sl) = sl then NONE else SOME(helper(sl)) 19 | end 20 | 21 | fun get_substitutions1(sl,s) = 22 | case sl of 23 | [] => [] 24 | | x::xs' => case all_except_option(s, x) of 25 | NONE => get_substitutions1(xs',s) 26 | | SOME l => l @ get_substitutions1(xs',s) 27 | 28 | fun get_substitutions2(sl,s) = 29 | let fun helper(li, acc) = 30 | case li of 31 | [] => acc 32 | | x::xs' => case all_except_option(s,x) of 33 | NONE => helper(xs',acc) 34 | | SOME l => helper(xs',l @ acc) 35 | in helper(sl,[]) 36 | end 37 | 38 | fun similar_names(sl,{first,middle,last}) = 39 | let fun helper(li) = 40 | case li of 41 | [] => [] 42 | | x::xs' => {first=x,last=last, middle=middle}::helper(xs') 43 | in {first=first,last=last, middle=middle}::helper(get_substitutions1(sl, first)) 44 | end 45 | 46 | (* you may assume that Num is always used with values 2, 3, ..., 10 47 | though it will not really come up *) 48 | datatype suit = Clubs | Diamonds | Hearts | Spades 49 | datatype rank = Jack | Queen | King | Ace | Num of int 50 | type card = suit * rank 51 | 52 | datatype color = Red | Black 53 | datatype move = Discard of card | Draw 54 | 55 | exception IllegalMove 56 | 57 | (* put your solutions for problem 2 here *) 58 | fun card_color(suit,rank) = 59 | case suit of 60 | Clubs => Black 61 | | Spades => Black 62 | | _ => Red 63 | 64 | fun card_value(suit,rank) = 65 | case rank of 66 | Ace => 11 67 | | Num x => x 68 | | _ => 10 69 | 70 | fun remove_card(cs,c,e) = 71 | case cs of 72 | [] => raise e 73 | | x::xs' => if x = c then xs' else x::remove_card(xs',c,e) 74 | 75 | fun all_same_color(cs) = 76 | case cs of 77 | [] => true 78 | | x::[] => true 79 | | x::xs'::[] => card_color(x) = card_color(xs') 80 | | x::xs'::xs'' => if card_color(x) = card_color(xs') then all_same_color(xs'::xs'') else false 81 | 82 | fun sum_cards(cs) = 83 | let fun helper(cl, acc) = 84 | case cl of 85 | [] => acc 86 | | x::xs' => helper(xs', card_value(x) + acc) 87 | in helper(cs,0) 88 | end 89 | 90 | fun score(cs,g) = 91 | let val divider = if all_same_color(cs) then 2 else 1 92 | val sum = sum_cards(cs) 93 | val prescore = if sum > g then 3 * (sum - g) else g - sum 94 | in prescore div divider 95 | end 96 | 97 | fun officiate(cds,moves,i) = 98 | let fun helper(c,m,h) = 99 | case (c,m,sum_cards(h) > i) of 100 | (_,_,true) => score(h,i) 101 | | (_,[],false) => score(h,i) 102 | | (_,(Discard crd)::xs',false) => helper(c,xs',remove_card(h,crd,IllegalMove)) 103 | | ([],(Draw)::xs',false) => score(h,i) 104 | | (x::xs',(Draw)::ys',false) => helper(xs',ys',x::h) 105 | in helper(cds,moves,[]) 106 | end; 107 | 108 | fun replace_one_ace(cs) = 109 | case cs of 110 | [] => [] 111 | | (c, Ace)::xs' => (c,Num(1))::xs' 112 | | card::xs' => card::replace_one_ace(xs') 113 | 114 | fun replace_one_ace_move(cs) = 115 | case cs of 116 | [] => [] 117 | | Discard(c, Ace)::xs' => Discard(c,Num(1))::xs' 118 | | card::xs' => card::replace_one_ace_move(xs') 119 | 120 | fun least_of(ls) = 121 | case ls of 122 | [] => 0 123 | | x::[] => x 124 | | x::xs' => let val min = least_of(xs') 125 | in if min < x 126 | then min 127 | else x 128 | end; 129 | 130 | fun score_challenge(cs,g) = 131 | let fun container(cs) = 132 | let val replaced = replace_one_ace(cs) 133 | in if cs = replaced 134 | then [score(cs,g)] 135 | else score(cs,g)::container(replaced) 136 | end 137 | in least_of(container(cs)) 138 | end; 139 | 140 | fun officiate_challenge(cds,moves,i) = 141 | let fun container(cs, moves) = 142 | let val replaced = replace_one_ace(cs) 143 | val repl_moves = replace_one_ace_move(moves) 144 | in if cs = replaced 145 | then [officiate(cs,moves,i)] 146 | else officiate(cs,moves,i)::container(replaced, repl_moves) 147 | end 148 | in least_of(container(cds, moves)) 149 | end; 150 | 151 | fun careful_player(cs,g) = 152 | let fun research_discard(held, new_card, total_value) = 153 | case held of 154 | [] => NONE 155 | | card::xs' => if total_value - card_value(card) + card_value(new_card) = g 156 | then SOME([Discard(card),Draw]) 157 | else research_discard(xs', new_card, total_value) 158 | 159 | fun helper(cs,held,moves) = 160 | case (cs, score(held,g) = 0) of 161 | (_,true) => moves 162 | | ([],false) => moves 163 | | (card::xs',false) => if sum_cards(held) <= g - 11 164 | then helper(xs',held@[card],moves@[Draw]) 165 | else case research_discard(held, card, sum_cards(held)) of 166 | NONE => moves 167 | | SOME(move) => helper(xs',held@[card],moves@move) 168 | in helper(cs,[],[]) 169 | end; 170 | 171 | use "johnson_hw2_test.sml"; 172 | 173 | (* 174 | f([(Clubs,Ace),(Hearts,Num(5)),(Spades,Ace),(Clubs,Jack)],22); 175 | *) 176 | -------------------------------------------------------------------------------- /2013/hw2/johnson_hw2.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | fun all_except_option(s, sl) = 11 | case sl of 12 | [] => NONE 13 | | x::[] => SOME [] 14 | | x::xs' => if same_string(s,x) then SOME xs' else all_except_option(s, xs') 15 | 16 | (* you may assume that Num is always used with values 2, 3, ..., 10 17 | though it will not really come up *) 18 | datatype suit = Clubs | Diamonds | Hearts | Spades 19 | datatype rank = Jack | Queen | King | Ace | Num of int 20 | type card = suit * rank 21 | 22 | datatype color = Red | Black 23 | datatype move = Discard of card | Draw 24 | 25 | exception IllegalMove 26 | 27 | (* put your solutions for problem 2 here *) 28 | 29 | fun officiate(c,m,i) = i; 30 | use "johnson_hw2_test.sml"; 31 | -------------------------------------------------------------------------------- /2013/hw2/johnson_hw2_test.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Tests *) 2 | 3 | val s1 = "CIvuNCJacBmzmN" 4 | val s2 = "xJeC3Oe6nJV4Cg" 5 | val s3 = "7IK3QAz2kNRCLs" 6 | val s4 = "i2oqTL6VTvJLUy" 7 | val s5 = "PMA3UfR5oYARjA" 8 | val s6 = "qoA5sTMLzuDRmb" 9 | val s7 = "MTmxbwXCSt5YLB" 10 | val s8 = "pp7htnOE3ag9Lq" 11 | val s9 = "urpWliQU08Gnk8" 12 | val s10 = "He1lIb6X0iu8IX" 13 | 14 | val sl1 = [s1,s2,s3,s4,s5,s6,s7,s8,s9,s10] 15 | val sl2 = ""::sl1 16 | val sl3 = [] 17 | val sl4 = [""] 18 | val sl5 = ["1"]; 19 | all_except_option("", sl2) = SOME sl1; 20 | all_except_option(s1,sl1) = SOME (tl sl1); 21 | all_except_option(s1,sl2) = SOME ""::(tl sl1); 22 | all_except_option(s2,sl3) = NONE; 23 | all_except_option("",sl1) = SOME sl1; 24 | all_except_option("",sl4) = SOME []; 25 | all_except_option("random",sl4) = SOME sl4; 26 | all_except_option("1",sl5) = SOME []; 27 | 28 | (* These are just two tests for problem 2; you will want more. 29 | 30 | Naturally these tests and your tests will use bindings defined 31 | in your solution, in particular the officiate function, 32 | so they will not type-check if officiate is not defined. 33 | *) 34 | 35 | fun provided_test1 () = (* correct behavior: raise IllegalMove *) 36 | let val cards = [(Clubs,Jack),(Spades,Num(8))] 37 | val moves = [Draw,Discard(Hearts,Jack)] 38 | in 39 | officiate(cards,moves,42) 40 | end 41 | 42 | fun provided_test2 () = (* correct behavior: return 3 *) 43 | let val cards = [(Clubs,Ace),(Spades,Ace),(Clubs,Ace),(Spades,Ace)] 44 | val moves = [Draw,Draw,Draw,Draw,Draw] 45 | in 46 | officiate(cards,moves,42) 47 | end 48 | -------------------------------------------------------------------------------- /2013/hw2/unit2notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw2/unit2notes.pdf -------------------------------------------------------------------------------- /2013/hw3/#johnson_hw3.sml#: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** you can put all your code here ****) 30 | fun only_capitals(ls) = List.filter (fn(x) => case size x of 31 | 0 => false 32 | | _ => Char.isUpper(String.sub(x,0))) ls 33 | 34 | fun longest_string1(ls) = foldl(fn(x,y) => if size x > size y then x else y) "" ls 35 | fun longest_string2(ls) = foldl(fn(x,y) => if size x >= size y then x else y) "" ls 36 | 37 | fun longest_string_helper f ls = List.foldl(fn(x,acc) => if f(size x, size acc) then x else acc) "" ls 38 | val longest_string3 = longest_string_helper (fn(x,y) => x > y) 39 | val longest_string4 = longest_string_helper (fn(x,y) => x >= y) 40 | 41 | val longest_capitalized = longest_string1 o only_capitals 42 | 43 | (*Important note for function below: 44 | fun rev_string(s: string) = implode o rev o explode s 45 | will not work 46 | 47 | http://stackoverflow.com/questions/12729640/why-is-there-type-mismatch-of-operator-and-operand 48 | *) 49 | fun rev_string(s) = (implode o rev o explode) s 50 | 51 | 52 | fun first_answer f ls = 53 | case ls of 54 | [] => raise NoAnswer 55 | | x::xs' => case f(x) of 56 | SOME v => v 57 | | NONE => first_answer f xs' 58 | 59 | fun all_answers f ls = 60 | let fun accumulator(ls,acc) = 61 | case ls of 62 | [] => SOME acc 63 | | x::xs' => case f(x) of 64 | SOME v => accumulator(xs',acc@v) 65 | | NONE => NONE 66 | in accumulator(ls,[]) 67 | end 68 | 69 | 70 | 71 | (* 72 | 9.a The function g takes three parameters in curried format, the first two are functions and the last one is a variable binding of type pattern. The function g eventually evaluates to type int. 73 | In essence, the function g computes the given pattern p according to the criteria of the two functions evaluating to a single value of type int. 74 | *) 75 | 76 | fun count_wildcards p = g (fn(_) => 1) (fn(_) => 0) p 77 | 78 | fun count_wild_and_variable_lengths p = g (fn(_) => 1) (fn(s) => String.size(s)) p 79 | fun count_some_var (s,p) = g (fn(_) => 0) (fn(v) => if v = s then 1 else 0) p 80 | 81 | fun check_pat p = 82 | let fun extract_Var p = 83 | case p of 84 | Variable s => [s] 85 | | TupleP ls => List.foldl(fn(p,acc) => acc@(extract_Var p)) [] ls 86 | | ConstructorP(_,p) => extract_Var p 87 | | _ => [] 88 | fun no_duplicates ls = 89 | case ls of 90 | [] => false 91 | | x::[] => true 92 | | x::xs' => if (List.exists (fn(y) => y = x) (xs')) then false else no_duplicates(xs') 93 | in no_duplicates(extract_Var p) 94 | end 95 | 96 | fun match(v,p) = 97 | case(v,p) of 98 | (_,Wildcard) => SOME [] 99 | | (v,Variable s) => SOME [(s,v)] 100 | | (Unit,UnitP) => SOME [] 101 | | (Const _, ConstP _) => SOME [] 102 | | (Tuple(vs), TupleP(ps)) => if List.length vs = List.length ps 103 | then all_answers (match) (ListPair.zip(vs,ps)) 104 | else NONE 105 | | (Constructor(s2,v),ConstructorP(s1,p)) => if s1 = s2 106 | then match(v,p) 107 | else NONE 108 | | _ => NONE 109 | 110 | fun first_match v lp = SOME (first_answer (match) (List.map(fn(x) => (v,x)) lp)) 111 | handle NoAnswer => NONE 112 | 113 | (**** for the challenge problem only ****) 114 | datatype typ = Anything (* any type of value is okay *) 115 | | UnitT (* type for Unit *) 116 | | IntT (* type for integers *) 117 | | TupleT of typ list (* tuple types *) 118 | | Datatype of string (* some named datatype *) 119 | 120 | (* 121 | type: ((string * string * typ) list) * (pattern list) -> typ option. 122 | 123 | *) 124 | fun typecheck_patterns -------------------------------------------------------------------------------- /2013/hw3/.#johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | SML@Kevins-MacBook-Pro.local.15485 -------------------------------------------------------------------------------- /2013/hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw3/hw3.pdf -------------------------------------------------------------------------------- /2013/hw3/hw3provided.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** for the challenge problem only ****) 30 | 31 | datatype typ = Anything 32 | | UnitT 33 | | IntT 34 | | TupleT of typ list 35 | | Datatype of string 36 | 37 | (**** you can put all your code here ****) 38 | -------------------------------------------------------------------------------- /2013/hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** for the challenge problem only ****) 30 | 31 | datatype typ = Anything 32 | | UnitT 33 | | IntT 34 | | TupleT of typ list 35 | | Datatype of string 36 | 37 | (**** you can put all your code here ****) 38 | fun only_capitals(ls) = List.filter (fn(x) => case size x of 39 | 0 => false 40 | | _ => Char.isUpper(String.sub(x,0))) ls 41 | 42 | fun longest_string1(ls) = foldl(fn(x,y) => if size x > size y then x else y) "" ls 43 | fun longest_string2(ls) = foldl(fn(x,y) => if size x >= size y then x else y) "" ls 44 | 45 | fun longest_string_helper f ls = List.foldl(fn(x,acc) => if f(size x, size acc) then x else acc) "" ls 46 | val longest_string3 = longest_string_helper (fn(x,y) => x > y) 47 | val longest_string4 = longest_string_helper (fn(x,y) => x >= y) 48 | 49 | val longest_capitalized = longest_string1 o only_capitals 50 | 51 | (*Important note for function below: 52 | fun rev_string(s: string) = implode o rev o explode s 53 | will not work 54 | 55 | http://stackoverflow.com/questions/12729640/why-is-there-type-mismatch-of-operator-and-operand 56 | *) 57 | fun rev_string(s) = (implode o rev o explode) s 58 | 59 | 60 | fun first_answer f ls = 61 | case ls of 62 | [] => raise NoAnswer 63 | | x::xs' => case f(x) of 64 | SOME v => v 65 | | NONE => first_answer f xs' 66 | 67 | fun all_answers f ls = 68 | let fun accumulator(ls,acc) = 69 | case ls of 70 | [] => SOME acc 71 | | x::xs' => case f(x) of 72 | SOME v => accumulator(xs',acc@v) 73 | | NONE => NONE 74 | in accumulator(ls,[]) 75 | end 76 | 77 | 78 | 79 | (* 80 | 9.a The function g takes three parameters in curried format, the first two are functions and the last one is a variable binding of type pattern. The function g eventually evaluates to type int. 81 | In essence, the function g computes the given pattern p according to the criteria of the two functions evaluating to a single value of type int. 82 | *) 83 | 84 | fun count_wildcards p = g (fn(_) => 1) (fn(_) => 0) p 85 | 86 | fun count_wild_and_variable_lengths p = g (fn(_) => 1) (fn(s) => String.size(s)) p 87 | fun count_some_var (s,p) = g (fn(_) => 0) (fn(v) => if v = s then 1 else 0) p 88 | 89 | fun check_pat p = 90 | let fun extract_Var p = 91 | case p of 92 | Variable s => [s] 93 | | TupleP ls => List.foldl(fn(p,acc) => acc@(extract_Var p)) [] ls 94 | | ConstructorP(_,p) => extract_Var p 95 | | _ => [] 96 | fun no_duplicates ls = 97 | case ls of 98 | [] => false 99 | | x::[] => true 100 | | x::xs' => if (List.exists (fn(y) => y = x) (xs')) then false else no_duplicates(xs') 101 | in no_duplicates(extract_Var p) 102 | end 103 | 104 | fun match(v,p) = 105 | case(v,p) of 106 | (_,Wildcard) => SOME [] 107 | | (v,Variable s) => SOME [(s,v)] 108 | | (Unit,UnitP) => SOME [] 109 | | (Const _, ConstP _) => SOME [] 110 | | (Tuple(vs), TupleP(ps)) => if List.length vs = List.length ps 111 | then all_answers (match) (ListPair.zip(vs,ps)) 112 | else NONE 113 | | (Constructor(s2,v),ConstructorP(s1,p)) => if s1 = s2 114 | then match(v,p) 115 | else NONE 116 | | _ => NONE 117 | 118 | fun first_match v lp = SOME (first_answer (match) (List.map(fn(x) => (v,x)) lp)) 119 | handle NoAnswer => NONE 120 | -------------------------------------------------------------------------------- /2013/hw3/johnson_hw3.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** for the challenge problem only ****) 30 | 31 | datatype typ = Anything 32 | | UnitT 33 | | IntT 34 | | TupleT of typ list 35 | | Datatype of string 36 | 37 | (**** you can put all your code here ****) 38 | -------------------------------------------------------------------------------- /2013/hw3/johnson_hw3_test.sml~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw3/johnson_hw3_test.sml~ -------------------------------------------------------------------------------- /2013/hw3/unit3notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw3/unit3notes.pdf -------------------------------------------------------------------------------- /2013/hw4/curry.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw4/curry.jpg -------------------------------------------------------------------------------- /2013/hw4/dan.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw4/dan.jpg -------------------------------------------------------------------------------- /2013/hw4/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw4/dog.jpg -------------------------------------------------------------------------------- /2013/hw4/dog2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw4/dog2.jpg -------------------------------------------------------------------------------- /2013/hw4/hw4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw4/hw4.pdf -------------------------------------------------------------------------------- /2013/hw4/hw4.rkt.txt: -------------------------------------------------------------------------------- 1 | 2 | #lang racket 3 | 4 | (provide (all-defined-out)) ;; so we can put tests in a second file 5 | 6 | ;; put your code below 7 | 8 | -------------------------------------------------------------------------------- /2013/hw4/hw4tests.rkt.txt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require "hw4.rkt") 4 | 5 | ;; A simple library for displaying a 2x3 grid of pictures: used 6 | ;; for fun in the tests below (look for "Tests Start Here"). 7 | 8 | (require (lib "graphics.rkt" "graphics")) 9 | 10 | (open-graphics) 11 | 12 | (define window-name "Programming Languages, Homework 4") 13 | (define window-width 700) 14 | (define window-height 500) 15 | (define border-size 100) 16 | 17 | (define approx-pic-width 200) 18 | (define approx-pic-height 200) 19 | (define pic-grid-width 3) 20 | (define pic-grid-height 2) 21 | 22 | (define (open-window) 23 | (open-viewport window-name window-width window-height)) 24 | 25 | (define (grid-posn-to-posn grid-posn) 26 | (when (>= grid-posn (* pic-grid-height pic-grid-width)) 27 | (error "picture grid does not have that many positions")) 28 | (let ([row (quotient grid-posn pic-grid-width)] 29 | [col (remainder grid-posn pic-grid-width)]) 30 | (make-posn (+ border-size (* approx-pic-width col)) 31 | (+ border-size (* approx-pic-height row))))) 32 | 33 | (define (place-picture window filename grid-posn) 34 | (let ([posn (grid-posn-to-posn grid-posn)]) 35 | ((clear-solid-rectangle window) posn approx-pic-width approx-pic-height) 36 | ((draw-pixmap window) filename posn))) 37 | 38 | (define (place-repeatedly window pause stream n) 39 | (when (> n 0) 40 | (let* ([next (stream)] 41 | [filename (cdar next)] 42 | [grid-posn (caar next)] 43 | [stream (cdr next)]) 44 | (place-picture window filename grid-posn) 45 | (sleep pause) 46 | (place-repeatedly window pause stream (- n 1))))) 47 | 48 | ;; Tests Start Here 49 | 50 | ; These definitions will work only after you do some of the problems 51 | ; so you need to comment them out until you are ready. 52 | ; Add more tests as appropriate, of course. 53 | 54 | (define nums (sequence 0 5 1)) 55 | 56 | (define files (string-append-map 57 | (list "dan" "dog" "curry" "dog2") 58 | ".jpg")) 59 | 60 | (define funny-test (stream-for-n-steps funny-number-stream 16)) 61 | 62 | ; a zero-argument function: call (one-visual-test) to open the graphics window, etc. 63 | (define (one-visual-test) 64 | (place-repeatedly (open-window) 0.5 (cycle-lists nums files) 27)) 65 | 66 | ; similar to previous but uses only two files and one position on the grid 67 | (define (visual-zero-only) 68 | (place-repeatedly (open-window) 0.5 (stream-add-zero dan-then-dog) 27)) 69 | -------------------------------------------------------------------------------- /2013/hw5/hw5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw5/hw5.pdf -------------------------------------------------------------------------------- /2013/hw5/hw5.rkt.txt: -------------------------------------------------------------------------------- 1 | ;; Programming Languages, Homework 5 2 | 3 | #lang racket 4 | (provide (all-defined-out)) ;; so we can put tests in a second file 5 | 6 | ;; definition of structures for MUPL programs - Do NOT change 7 | (struct var (string) #:transparent) ;; a variable, e.g., (var "foo") 8 | (struct int (num) #:transparent) ;; a constant number, e.g., (int 17) 9 | (struct add (e1 e2) #:transparent) ;; add two expressions 10 | (struct ifgreater (e1 e2 e3 e4) #:transparent) ;; if e1 > e2 then e3 else e4 11 | (struct fun (nameopt formal body) #:transparent) ;; a recursive(?) 1-argument function 12 | (struct call (funexp actual) #:transparent) ;; function call 13 | (struct mlet (var e body) #:transparent) ;; a local binding (let var = e in body) 14 | (struct apair (e1 e2) #:transparent) ;; make a new pair 15 | (struct fst (e) #:transparent) ;; get first part of a pair 16 | (struct snd (e) #:transparent) ;; get second part of a pair 17 | (struct aunit () #:transparent) ;; unit value -- good for ending a list 18 | (struct isaunit (e) #:transparent) ;; evaluate to 1 if e is unit else 0 19 | 20 | ;; a closure is not in "source" programs; it is what functions evaluate to 21 | (struct closure (env fun) #:transparent) 22 | 23 | ;; Problem 1 24 | 25 | ;; CHANGE (put your solutions here) 26 | 27 | ;; Problem 2 28 | 29 | ;; lookup a variable in an environment 30 | ;; Do NOT change this function 31 | (define (envlookup env str) 32 | (cond [(null? env) (error "unbound variable during evaluation" str)] 33 | [(equal? (car (car env)) str) (cdr (car env))] 34 | [#t (envlookup (cdr env) str)])) 35 | 36 | ;; Do NOT change the two cases given to you. 37 | ;; DO add more cases for other kinds of MUPL expressions. 38 | ;; We will test eval-under-env by calling it directly even though 39 | ;; "in real life" it would be a helper function of eval-exp. 40 | (define (eval-under-env e env) 41 | (cond [(var? e) 42 | (envlookup env (var-string e))] 43 | [(add? e) 44 | (let ([v1 (eval-under-env (add-e1 e) env)] 45 | [v2 (eval-under-env (add-e2 e) env)]) 46 | (if (and (int? v1) 47 | (int? v2)) 48 | (int (+ (int-num v1) 49 | (int-num v2))) 50 | (error "MUPL addition applied to non-number")))] 51 | ;; CHANGE add more cases here 52 | [#t (error (format "bad MUPL expression: ~v" e))])) 53 | 54 | ;; Do NOT change 55 | (define (eval-exp e) 56 | (eval-under-env e null)) 57 | 58 | ;; Problem 3 59 | 60 | (define (ifaunit e1 e2 e3) "CHANGE") 61 | 62 | (define (mlet* lstlst e2) "CHANGE") 63 | 64 | (define (ifeq e1 e2 e3 e4) "CHANGE") 65 | 66 | ;; Problem 4 67 | 68 | (define mupl-map "CHANGE") 69 | 70 | (define mupl-mapAddN 71 | (mlet "map" mupl-map 72 | "CHANGE (notice map is now in MUPL scope)")) 73 | 74 | ;; Challenge Problem 75 | 76 | (struct fun-challenge (nameopt formal body freevars) #:transparent) ;; a recursive(?) 1-argument function 77 | 78 | ;; We will test this function directly, so it must do 79 | ;; as described in the assignment 80 | (define (compute-free-vars e) "CHANGE") 81 | 82 | ;; Do NOT share code with eval-under-env because that will make grading 83 | ;; more difficult, so copy most of your interpreter here and make minor changes 84 | (define (eval-under-env-c e env) "CHANGE") 85 | 86 | ;; Do NOT change this 87 | (define (eval-exp-c e) 88 | (eval-under-env-c (compute-free-vars e) null)) 89 | -------------------------------------------------------------------------------- /2013/hw5/hw5tests.rkt.txt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require "hw5.rkt") 4 | 5 | ; a test case that uses problems 1, 2, and 4 6 | ; should produce (list (int 10) (int 11) (int 16)) 7 | (define test1 8 | (mupllist->racketlist 9 | (eval-exp (call (call mupl-mapAddN (int 7)) 10 | (racketlist->mupllist 11 | (list (int 3) (int 4) (int 9))))))) -------------------------------------------------------------------------------- /2013/hw6/hw6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw6/hw6.pdf -------------------------------------------------------------------------------- /2013/hw6/hw6assignment.rb: -------------------------------------------------------------------------------- 1 | # University of Washington, Programming Languages, Homework 6, hw6runner.rb 2 | 3 | # This is the only file you turn in, so do not modify the other files as 4 | # part of your solution. 5 | 6 | class MyPiece < Piece 7 | # The constant All_My_Pieces should be declared here 8 | 9 | # your enhancements here 10 | 11 | end 12 | 13 | class MyBoard < Board 14 | # your enhancements here 15 | 16 | end 17 | 18 | class MyTetris < Tetris 19 | # your enhancements here 20 | 21 | end 22 | 23 | 24 | -------------------------------------------------------------------------------- /2013/hw6/hw6graphics.rb: -------------------------------------------------------------------------------- 1 | # University of Washington, Programming Languages, Homework 6, hw6graphics.rb 2 | 3 | # This file provides an interface to a wrapped Tk library. The auto-grader will 4 | # swap it out to use a different, non-Tk backend. 5 | 6 | require 'tk' 7 | 8 | class TetrisRoot 9 | def initialize 10 | @root = TkRoot.new('height' => 615, 'width' => 205, 11 | 'background' => 'lightblue') {title "Tetris"} 12 | end 13 | 14 | def bind(char, callback) 15 | @root.bind(char, callback) 16 | end 17 | 18 | # Necessary so we can unwrap before passing to Tk in some instances. 19 | # Student code MUST NOT CALL THIS. 20 | attr_reader :root 21 | end 22 | 23 | class TetrisTimer 24 | def initialize 25 | @timer = TkTimer.new 26 | end 27 | 28 | def stop 29 | @timer.stop 30 | end 31 | 32 | def start(delay, callback) 33 | @timer.start(delay, callback) 34 | end 35 | end 36 | 37 | class TetrisCanvas 38 | def initialize 39 | @canvas = TkCanvas.new('background' => 'grey') 40 | end 41 | 42 | def place(height, width, x, y) 43 | @canvas.place('height' => height, 'width' => width, 'x' => x, 'y' => y) 44 | end 45 | 46 | def unplace 47 | @canvas.unplace 48 | end 49 | 50 | def delete 51 | @canvas.delete 52 | end 53 | 54 | # Necessary so we can unwrap before passing to Tk in some instances. 55 | # Student code MUST NOT CALL THIS. 56 | attr_reader :canvas 57 | end 58 | 59 | class TetrisLabel 60 | def initialize(wrapped_root, &options) 61 | unwrapped_root = wrapped_root.root 62 | @label = TkLabel.new(unwrapped_root, &options) 63 | end 64 | 65 | def place(height, width, x, y) 66 | @label.place('height' => height, 'width' => width, 'x' => x, 'y' => y) 67 | end 68 | 69 | def text(str) 70 | @label.text(str) 71 | end 72 | end 73 | 74 | class TetrisButton 75 | def initialize(label, color) 76 | @button = TkButton.new do 77 | text label 78 | background color 79 | command (proc {yield}) 80 | end 81 | end 82 | 83 | def place(height, width, x, y) 84 | @button.place('height' => height, 'width' => width, 'x' => x, 'y' => y) 85 | end 86 | end 87 | 88 | class TetrisRect 89 | def initialize(wrapped_canvas, a, b, c, d, color) 90 | unwrapped_canvas = wrapped_canvas.canvas 91 | @rect = TkcRectangle.new(unwrapped_canvas, a, b, c, d, 92 | 'outline' => 'black', 'fill' => color) 93 | end 94 | 95 | def remove 96 | @rect.remove 97 | end 98 | 99 | def move(dx, dy) 100 | @rect.move(dx, dy) 101 | end 102 | 103 | end 104 | 105 | def mainLoop 106 | Tk.mainloop 107 | end 108 | 109 | def exitProgram 110 | Tk.exit 111 | end 112 | -------------------------------------------------------------------------------- /2013/hw6/hw6runner.rb: -------------------------------------------------------------------------------- 1 | # University of Washington, Programming Languages, Homework 6, hw6runner.rb 2 | 3 | require_relative './hw6provided' 4 | require_relative './hw6assignment' 5 | 6 | def runTetris 7 | Tetris.new 8 | mainLoop 9 | end 10 | 11 | def runMyTetris 12 | MyTetris.new 13 | mainLoop 14 | end 15 | 16 | if ARGV.count == 0 17 | runMyTetris 18 | elsif ARGV.count != 1 19 | puts "usage: hw6runner.rb [enhanced | original]" 20 | elsif ARGV[0] == "enhanced" 21 | runMyTetris 22 | elsif ARGV[0] == "original" 23 | runTetris 24 | else 25 | puts "usage: hw6runner.rb [enhanced | original]" 26 | end 27 | 28 | -------------------------------------------------------------------------------- /2013/hw7/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw7/.DS_Store -------------------------------------------------------------------------------- /2013/hw7/hw7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/2013/hw7/hw7.pdf -------------------------------------------------------------------------------- /2013/hw7/hw7.rb: -------------------------------------------------------------------------------- 1 | # CSE341 Spring 2013, Homework 7, hw7.rb (see also SML code) 2 | 3 | # a little language for 2D geometry objects 4 | 5 | # each subclass of GeometryExpression, including subclasses of GeometryValue, 6 | # needs to respond to messages preprocess_prog and eval_prog 7 | # 8 | # each subclass of GeometryValue additionally needs: 9 | # * shift 10 | # * intersect, which uses the double-dispatch pattern 11 | # * intersectPoint, intersectLine, and intersectVerticalLine for 12 | # for being called by intersect of appropriate clases and doing 13 | # the correct intersection calculuation 14 | # * (We would need intersectNoPoints and intersectLineSegment, but these 15 | # are provided by GeometryValue and should not be overridden.) 16 | # * intersectWithSegmentAsLineResult, which is used by 17 | # intersectLineSegment as described in the assignment 18 | # 19 | # you can define other helper methods, but will not find much need to 20 | 21 | # Note: geometry objects should be immutable: assign to fields only during 22 | # object construction 23 | 24 | # Note: For eval_prog, represent environments as arrays of 2-element arrays 25 | # as described in the assignment 26 | 27 | class GeometryExpression 28 | # do *not* change this class definition 29 | Epsilon = 0.00001 30 | end 31 | 32 | class GeometryValue 33 | # do *not* change methods in this class definition 34 | # you can add methods if you wish 35 | 36 | private 37 | # some helper methods that may be generally useful 38 | def real_close(r1,r2) 39 | (r1 - r2).abs < GeometryExpression::Epsilon 40 | end 41 | def real_close_point(x1,y1,x2,y2) 42 | real_close(x1,x2) && real_close(y1,y2) 43 | end 44 | # two_points_to_line could return a Line or a VerticalLine 45 | def two_points_to_line(x1,y1,x2,y2) 46 | if real_close(x1,x2) 47 | VerticalLine.new x1 48 | else 49 | m = (y2 - y1).to_f / (x2 - x1) 50 | b = y1 - m * x1 51 | Line.new(m,b) 52 | end 53 | end 54 | 55 | public 56 | # we put this in this class so all subclasses can inherit it: 57 | # the intersection of self with a NoPoints is a NoPoints object 58 | def intersectNoPoints np 59 | np # could also have NoPoints.new here instead 60 | end 61 | 62 | # we put this in this class so all subclasses can inhert it: 63 | # the intersection of self with a LineSegment is computed by 64 | # first intersecting with the line containing the segment and then 65 | # calling the result's intersectWithSegmentAsLineResult with the segment 66 | def intersectLineSegment seg 67 | line_result = intersect(two_points_to_line(seg.x1,seg.y1,seg.x2,seg.y2)) 68 | line_result.intersectWithSegmentAsLineResult seg 69 | end 70 | end 71 | 72 | class NoPoints < GeometryValue 73 | # do *not* change this class definition: everything is done for you 74 | # (although this is the easiest class, it shows what methods every subclass 75 | # of geometry values needs) 76 | 77 | # Note: no initialize method only because there is nothing it needs to do 78 | def eval_prog env 79 | self # all values evaluate to self 80 | end 81 | def preprocess_prog 82 | self # no pre-processing to do here 83 | end 84 | def shift(dx,dy) 85 | self # shifting no-points is no-points 86 | end 87 | def intersect other 88 | other.intersectNoPoints self # will be NoPoints but follow double-dispatch 89 | end 90 | def intersectPoint p 91 | self # intersection with point and no-points is no-points 92 | end 93 | def intersectLine line 94 | self # intersection with line and no-points is no-points 95 | end 96 | def intersectVerticalLine vline 97 | self # intersection with line and no-points is no-points 98 | end 99 | # if self is the intersection of (1) some shape s and (2) 100 | # the line containing seg, then we return the intersection of the 101 | # shape s and the seg. seg is an instance of LineSegment 102 | def intersectWithSegmentAsLineResult seg 103 | self 104 | end 105 | end 106 | 107 | 108 | class Point < GeometryValue 109 | # *add* methods to this class -- do *not* change given code and do not 110 | # override any methods 111 | 112 | # Note: You may want a private helper method like the local 113 | # helper function inbetween in the ML code 114 | attr_reader :x, :y 115 | def initialize(x,y) 116 | @x = x 117 | @y = y 118 | end 119 | end 120 | 121 | class Line < GeometryValue 122 | # *add* methods to this class -- do *not* change given code and do not 123 | # override any methods 124 | attr_reader :m, :b 125 | def initialize(m,b) 126 | @m = m 127 | @b = b 128 | end 129 | end 130 | 131 | class VerticalLine < GeometryValue 132 | # *add* methods to this class -- do *not* change given code and do not 133 | # override any methods 134 | attr_reader :x 135 | def initialize x 136 | @x = x 137 | end 138 | end 139 | 140 | class LineSegment < GeometryValue 141 | # *add* methods to this class -- do *not* change given code and do not 142 | # override any methods 143 | # Note: This is the most difficult class. In the sample solution, 144 | # preprocess_prog is about 15 lines long and 145 | # intersectWithSegmentAsLineResult is about 40 lines long 146 | attr_reader :x1, :y1, :x2, :y2 147 | def initialize (x1,y1,x2,y2) 148 | @x1 = x1 149 | @y1 = y1 150 | @x2 = x2 151 | @y2 = y2 152 | end 153 | end 154 | 155 | # Note: there is no need for getter methods for the non-value classes 156 | 157 | class Intersect < GeometryExpression 158 | # *add* methods to this class -- do *not* change given code and do not 159 | # override any methods 160 | def initialize(e1,e2) 161 | @e1 = e1 162 | @e2 = e2 163 | end 164 | end 165 | 166 | class Let < GeometryExpression 167 | # *add* methods to this class -- do *not* change given code and do not 168 | # override any methods 169 | # Note: Look at Var to guide how you implement Let 170 | def initialize(s,e1,e2) 171 | @s = s 172 | @e1 = e1 173 | @e2 = e2 174 | end 175 | end 176 | 177 | class Var < GeometryExpression 178 | # *add* methods to this class -- do *not* change given code and do not 179 | # override any methods 180 | def initialize s 181 | @s = s 182 | end 183 | def eval_prog env # remember: do not change this method 184 | pr = env.assoc @s 185 | raise "undefined variable" if pr.nil? 186 | pr[1] 187 | end 188 | end 189 | 190 | class Shift < GeometryExpression 191 | # *add* methods to this class -- do *not* change given code and do not 192 | # override any methods 193 | def initialize(dx,dy,e) 194 | @dx = dx 195 | @dy = dy 196 | @e = e 197 | end 198 | end 199 | -------------------------------------------------------------------------------- /2013/hw7/hw7.sml: -------------------------------------------------------------------------------- 1 | (* CSE341 Spring 2013, Homework 7, hw7.sml (see also Ruby code) *) 2 | 3 | (* Do not make changes to this code except where you see comments containing 4 | the word CHANGE. *) 5 | 6 | (* expressions in a little language for 2D geometry objects 7 | values: points, lines, vertical lines, line segments 8 | other expressions: intersection of two expressions, lets, variables, 9 | (shifts added by you) 10 | *) 11 | datatype geom_exp = 12 | NoPoints 13 | | Point of real * real (* represents point (x,y) *) 14 | | Line of real * real (* represents line (slope, intercept) *) 15 | | VerticalLine of real (* x value *) 16 | | LineSegment of real * real * real * real (* x1,y1 to x2,y2 *) 17 | | Intersect of geom_exp * geom_exp (* intersection expression *) 18 | | Let of string * geom_exp * geom_exp (* let s = e1 in e2 *) 19 | | Var of string 20 | (* CHANGE add shifts for expressions of the form Shift(deltaX, deltaY, exp *) 21 | 22 | exception BadProgram of string 23 | exception Impossible of string 24 | 25 | (* helper functions for comparing real numbers since rounding means 26 | we should never compare for equality *) 27 | 28 | val epsilon = 0.00001 29 | 30 | fun real_close (r1,r2) = 31 | (Real.abs (r1 - r2)) < epsilon 32 | 33 | (* notice curried *) 34 | fun real_close_point (x1,y1) (x2,y2) = 35 | real_close(x1,x2) andalso real_close(y1,y2) 36 | 37 | (* helper function to return the Line or VerticalLine containing 38 | points (x1,y1) and (x2,y2). Actually used only when intersecting 39 | line segments, but might be generally useful *) 40 | fun two_points_to_line (x1,y1,x2,y2) = 41 | if real_close(x1,x2) 42 | then VerticalLine x1 43 | else 44 | let 45 | val m = (y2 - y1) / (x2 - x1) 46 | val b = y1 - m * x1 47 | in 48 | Line(m,b) 49 | end 50 | 51 | (* helper function for interpreter: return value that is the intersection 52 | of the arguments: 25 cases because there are 5 kinds of values, but 53 | many cases can be combined, especially because intersection is commutative. 54 | Do *not* call this function with non-values (e.g., shifts or lets) 55 | *) 56 | fun intersect (v1,v2) = 57 | case (v1,v2) of 58 | 59 | (NoPoints, _) => NoPoints (* 5 cases *) 60 | | (_, NoPoints) => NoPoints (* 4 additional cases *) 61 | 62 | | (Point p1, Point p2) => if real_close_point p1 p2 63 | then v1 64 | else NoPoints 65 | 66 | | (Point (x,y), Line (m,b)) => if real_close(y, m * x + b) 67 | then v1 68 | else NoPoints 69 | 70 | | (Point (x1,_), VerticalLine x2) => if real_close(x1,x2) 71 | then v1 72 | else NoPoints 73 | 74 | | (Point _, LineSegment seg) => intersect(v2,v1) 75 | 76 | | (Line _, Point _) => intersect(v2,v1) 77 | 78 | | (Line (m1,b1), Line (m2,b2)) => 79 | if real_close(m1,m2) 80 | then (if real_close(b1,b2) 81 | then v1 (* same line *) 82 | else NoPoints) (* parallel lines do not intersect *) 83 | else 84 | let (* one-point intersection *) 85 | val x = (b2 - b1) / (m1 - m2) 86 | val y = m1 * x + b1 87 | in 88 | Point (x,y) 89 | end 90 | 91 | | (Line (m1,b1), VerticalLine x2) => Point(x2, m1 * x2 + b1) 92 | 93 | | (Line _, LineSegment _) => intersect(v2,v1) 94 | 95 | | (VerticalLine _, Point _) => intersect(v2,v1) 96 | | (VerticalLine _, Line _) => intersect(v2,v1) 97 | 98 | | (VerticalLine x1, VerticalLine x2) => 99 | if real_close(x1,x2) 100 | then v1 (* same line *) 101 | else NoPoints (* parallel *) 102 | 103 | | (VerticalLine _, LineSegment seg) => intersect(v2,v1) 104 | 105 | | (LineSegment seg, _) => 106 | (* the hard case, actually 4 cases because v2 could be a point, 107 | line, vertical line, or line segment *) 108 | (* First compute the intersection of (1) the line containing the segment 109 | and (2) v2. Then use that result to compute what we need. *) 110 | (case intersect(two_points_to_line seg, v2) of 111 | NoPoints => NoPoints 112 | | Point(x0,y0) => (* see if the point is within the segment bounds *) 113 | (* assumes v1 was properly preprocessed *) 114 | let 115 | fun inbetween(v,end1,end2) = 116 | (end1 - epsilon <= v andalso v <= end2 + epsilon) 117 | orelse (end2 - epsilon <= v andalso v <= end1 + epsilon) 118 | val (x1,y1,x2,y2) = seg 119 | in 120 | if inbetween(x0,x1,x2) andalso inbetween(y0,y1,y2) 121 | then Point(x0,y0) 122 | else NoPoints 123 | end 124 | | Line _ => v1 (* so segment seg is on line v2 *) 125 | | VerticalLine _ => v1 (* so segment seg is on vertical-line v2 *) 126 | | LineSegment seg2 => 127 | (* the hard case in the hard case: seg and seg2 are on the same 128 | line (or vertical line), but they could be (1) disjoint or 129 | (2) overlapping or (3) one inside the other or (4) just touching. 130 | And we treat vertical segments differently, so there are 4*2 cases. 131 | *) 132 | let 133 | val (x1start,y1start,x1end,y1end) = seg 134 | val (x2start,y2start,x2end,y2end) = seg2 135 | in 136 | if real_close(x1start,x1end) 137 | then (* the segments are on a vertical line *) 138 | (* let segment a start at or below start of segment b *) 139 | let 140 | val ((aXstart,aYstart,aXend,aYend), 141 | (bXstart,bYstart,bXend,bYend)) = if y1start < y2start 142 | then (seg,seg2) 143 | else (seg2,seg) 144 | in 145 | if real_close(aYend,bYstart) 146 | then Point (aXend,aYend) (* just touching *) 147 | else if aYend < bYstart 148 | then NoPoints (* disjoint *) 149 | else if aYend > bYend 150 | then LineSegment(bXstart,bYstart,bXend,bYend) (* b inside a *) 151 | else LineSegment(bXstart,bYstart,aXend,aYend) (* overlapping *) 152 | end 153 | else (* the segments are on a (non-vertical) line *) 154 | (* let segment a start at or to the left of start of segment b *) 155 | let 156 | val ((aXstart,aYstart,aXend,aYend), 157 | (bXstart,bYstart,bXend,bYend)) = if x1start < x2start 158 | then (seg,seg2) 159 | else (seg2,seg) 160 | in 161 | if real_close(aXend,bXstart) 162 | then Point (aXend,aYend) (* just touching *) 163 | else if aXend < bXstart 164 | then NoPoints (* disjoint *) 165 | else if aXend > bXend 166 | then LineSegment(bXstart,bYstart,bXend,bYend) (* b inside a *) 167 | else LineSegment(bXstart,bYstart,aXend,aYend) (* overlapping *) 168 | end 169 | end 170 | | _ => raise Impossible "bad result from intersecting with a line") 171 | | _ => raise Impossible "bad call to intersect: only for shape values" 172 | 173 | (* interpreter for our language: 174 | * takes a geometry expression and returns a geometry value 175 | * for simplicity we have the top-level function take an environment, 176 | (which should be [] for the whole program 177 | * we assume the expression e has already been "preprocessed" as described 178 | in the homework assignment: 179 | * line segments are not actually points (endpoints not real close) 180 | * lines segment have left (or, if vertical, bottom) coordinate first 181 | *) 182 | 183 | fun eval_prog (e,env) = 184 | case e of 185 | NoPoints => e (* first 5 cases are all values, so no computation *) 186 | | Point _ => e 187 | | Line _ => e 188 | | VerticalLine _ => e 189 | | LineSegment _ => e 190 | | Var s => 191 | (case List.find (fn (s2,v) => s=s2) env of 192 | NONE => raise BadProgram("var not found: " ^ s) 193 | | SOME (_,v) => v) 194 | | Let(s,e1,e2) => eval_prog (e2, ((s, eval_prog(e1,env)) :: env)) 195 | | Intersect(e1,e2) => intersect(eval_prog(e1,env), eval_prog(e2, env)) 196 | (* CHANGE: Add a case for Shift expressions *) 197 | 198 | (* CHANGE: Add function preprocess_prog of type geom_exp -> geom_exp *) 199 | -------------------------------------------------------------------------------- /2013/hw7/hw7testsprovided.rb: -------------------------------------------------------------------------------- 1 | require "./hw7.rb" 2 | 3 | =begin 4 | CSE341 Spring 2013, Homework 7, Provided Tests 5 | Will not work completely until you implement all the classes and their methods 6 | 7 | Will print only if code has errors; prints nothing if all tests pass 8 | 9 | These tests do NOT cover all the various cases, especially for intersection 10 | =end 11 | 12 | #Constants for testing 13 | ZERO = 0.0 14 | ONE = 1.0 15 | TWO = 2.0 16 | THREE = 3.0 17 | FOUR = 4.0 18 | FIVE = 5.0 19 | SIX = 6.0 20 | SEVEN = 7.0 21 | TEN = 10.0 22 | 23 | #Point Tests 24 | a = Point.new(THREE,FIVE) 25 | if not (a.x == THREE and a.y == FIVE) 26 | puts "Point is not initialized properly" 27 | end 28 | if not (a.eval_prog([]) == a) 29 | puts "Point eval_prog should return self" 30 | end 31 | if not (a.preprocess_prog == a) 32 | puts "Point preprocess_prog should return self" 33 | end 34 | a1 = a.shift(THREE,FIVE) 35 | if not (a1.x == SIX and a1.y == TEN) 36 | puts "Point shift not working properly" 37 | end 38 | a2 = a.intersect(Point.new(THREE,FIVE)) 39 | if not (a2.x == THREE and a2.y == FIVE) 40 | puts "Point intersect not working properly" 41 | end 42 | a3 = a.intersect(Point.new(FOUR,FIVE)) 43 | if not (a3.is_a? NoPoints) 44 | puts "Point intersect not working properly" 45 | end 46 | 47 | #Line Tests 48 | b = Line.new(THREE,FIVE) 49 | if not (b.m == THREE and b.b == FIVE) 50 | puts "Line not initialized properly" 51 | end 52 | if not (b.eval_prog([]) == b) 53 | puts "Line eval_prog should return self" 54 | end 55 | if not (b.preprocess_prog == b) 56 | puts "Line preprocess_prog should return self" 57 | end 58 | 59 | b1 = b.shift(THREE,FIVE) 60 | if not (b1.m == THREE and b1.b == ONE) 61 | puts "Line shift not working properly" 62 | end 63 | 64 | b2 = b.intersect(Line.new(THREE,FIVE)) 65 | if not (((b2.is_a? Line)) and b2.m == THREE and b2.b == FIVE) 66 | puts "Line intersect not working properly" 67 | end 68 | b3 = b.intersect(Line.new(THREE,FOUR)) 69 | if not ((b3.is_a? NoPoints)) 70 | puts "Line intersect not working properly" 71 | end 72 | 73 | #VerticalLine Tests 74 | c = VerticalLine.new(THREE) 75 | if not (c.x == THREE) 76 | puts "VerticalLine not initialized properly" 77 | end 78 | 79 | if not (c.eval_prog([]) == c) 80 | puts "VerticalLine eval_prog should return self" 81 | end 82 | if not (c.preprocess_prog == c) 83 | puts "VerticalLine preprocess_prog should return self" 84 | end 85 | c1 = c.shift(THREE,FIVE) 86 | if not (c1.x == SIX) 87 | puts "VerticalLine shift not working properly" 88 | end 89 | c2 = c.intersect(VerticalLine.new(THREE)) 90 | if not ((c2.is_a? VerticalLine) and c2.x == THREE ) 91 | puts "VerticalLine intersect not working properly" 92 | end 93 | c3 = c.intersect(VerticalLine.new(FOUR)) 94 | if not ((c3.is_a? NoPoints)) 95 | puts "VerticalLine intersect not working properly" 96 | end 97 | 98 | #LineSegment Tests 99 | d = LineSegment.new(ONE,TWO,-THREE,-FOUR) 100 | if not (d.eval_prog([]) == d) 101 | puts "LineSegement eval_prog should return self" 102 | end 103 | d1 = LineSegment.new(ONE,TWO,ONE,TWO) 104 | d2 = d1.preprocess_prog 105 | if not ((d2.is_a? Point)and d2.x == ONE and d2.y == TWO) 106 | puts "LineSegment preprocess_prog should convert to a Point" 107 | puts "if ends of segment are real_close" 108 | end 109 | 110 | d = d.preprocess_prog 111 | if not (d.x1 == -THREE and d.y1 == -FOUR and d.x2 == ONE and d.y2 == TWO) 112 | puts "LineSegment preprocess_prog should make x1 and y1" 113 | puts "on the left of x2 and y2" 114 | end 115 | 116 | d3 = d.shift(THREE,FIVE) 117 | if not (d3.x1 == ZERO and d3.y1 == ONE and d3.x2 == FOUR and d3.y2 == SEVEN) 118 | puts "LineSegment shift not working properly" 119 | end 120 | 121 | d4 = d.intersect(LineSegment.new(-THREE,-FOUR,ONE,TWO)) 122 | if not (((d4.is_a? LineSegment)) and d4.x1 == -THREE and d4.y1 == -FOUR and d4.x2 == ONE and d4.y2 == TWO) 123 | puts "LineSegment intersect not working properly" 124 | end 125 | d5 = d.intersect(LineSegment.new(TWO,THREE,FOUR,FIVE)) 126 | if not ((d5.is_a? NoPoints)) 127 | puts "LineSegment intersect not working properly" 128 | end 129 | 130 | #Intersect Tests 131 | i = Intersect.new(LineSegment.new(-ONE,-TWO,THREE,FOUR), LineSegment.new(THREE,FOUR,-ONE,-TWO)) 132 | i1 = i.preprocess_prog.eval_prog([]) 133 | if not (i1.x1 == -ONE and i1.y1 == -TWO and i1.x2 == THREE and i1.y2 == FOUR) 134 | puts "Intersect eval_prog should return the intersect between e1 and e2" 135 | end 136 | 137 | #Var Tests 138 | v = Var.new("a") 139 | v1 = v.eval_prog([["a", Point.new(THREE,FIVE)]]) 140 | if not ((v1.is_a? Point) and v1.x == THREE and v1.y == FIVE) 141 | puts "Var eval_prog is not working properly" 142 | end 143 | if not (v1.preprocess_prog == v1) 144 | puts "Var preprocess_prog should return self" 145 | end 146 | 147 | #Let Tests 148 | l = Let.new("a", LineSegment.new(-ONE,-TWO,THREE,FOUR), 149 | Intersect.new(Var.new("a"),LineSegment.new(THREE,FOUR,-ONE,-TWO))) 150 | l1 = l.preprocess_prog.eval_prog([]) 151 | if not (l1.x1 == -ONE and l1.y1 == -TWO and l1.x2 == THREE and l1.y2 == FOUR) 152 | puts "Let eval_prog should evaluate e2 after adding [s, e1] to the environment" 153 | end 154 | 155 | #Let Variable Shadowing Test 156 | l2 = Let.new("a", LineSegment.new(-ONE, -TWO, THREE, FOUR), 157 | Let.new("b", LineSegment.new(THREE,FOUR,-ONE,-TWO), Intersect.new(Var.new("a"),Var.new("b")))) 158 | l2 = l2.preprocess_prog.eval_prog([["a",Point.new(0,0)]]) 159 | if not (l2.x1 == -ONE and l2.y1 == -TWO and l2.x2 == THREE and l2.y2 == FOUR) 160 | puts "Let eval_prog should evaluate e2 after adding [s, e1] to the environment" 161 | end 162 | 163 | 164 | #Shift Tests 165 | s = Shift.new(THREE,FIVE,LineSegment.new(-ONE,-TWO,THREE,FOUR)) 166 | s1 = s.preprocess_prog.eval_prog([]) 167 | if not (s1.x1 == TWO and s1.y1 == THREE and s1.x2 == SIX and s1.y2 == 9) 168 | puts "Shift should shift e by dx and dy" 169 | end 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /2013/hw7/hw7testsprovided.sml: -------------------------------------------------------------------------------- 1 | (* CSE341 Spring 2013, Homework 7, Provided Tests *) 2 | (* Will not compile until you implement preprocess and eval_prog *) 3 | 4 | (* These tests do NOT cover all the various cases, especially for intersection *) 5 | 6 | use "hw7.sml"; 7 | 8 | (* Must implement preprocess_prog and Shift before running these tests *) 9 | 10 | fun real_equal(x,y) = Real.compare(x,y) = General.EQUAL; 11 | 12 | (* Preprocess tests *) 13 | let 14 | val Point(a,b) = preprocess_prog(LineSegment(3.2,4.1,3.2,4.1)) 15 | val Point(c,d) = Point(3.2,4.1) 16 | in 17 | if real_equal(a,c) andalso real_equal(b,d) 18 | then (print "preprocess converts a LineSegment to a Point successfully\n") 19 | else (print "preprocess does not convert a LineSegment to a Point succesfully\n") 20 | end; 21 | 22 | let 23 | val LineSegment(a,b,c,d) = preprocess_prog (LineSegment(3.2,4.1,~3.2,~4.1)) 24 | val LineSegment(e,f,g,h) = LineSegment(~3.2,~4.1,3.2,4.1) 25 | in 26 | if real_equal(a,e) andalso real_equal(b,f) andalso real_equal(c,g) andalso real_equal(d,h) 27 | then (print "preprocess flips an improper LineSegment successfully\n") 28 | else (print "preprocess does not flip an improper LineSegment successfully\n") 29 | end; 30 | 31 | (* eval_prog tests with Shift*) 32 | let 33 | val Point(a,b) = (eval_prog (preprocess_prog (Shift(3.0, 4.0, Point(4.0,4.0))), [])) 34 | val Point(c,d) = Point(7.0,8.0) 35 | in 36 | if real_equal(a,c) andalso real_equal(b,d) 37 | then (print "eval_prog with empty environment worked\n") 38 | else (print "eval_prog with empty environment is not working properly\n") 39 | end; 40 | 41 | (* Using a Var *) 42 | let 43 | val Point(a,b) = (eval_prog (Shift(3.0,4.0,Var "a"), [("a",Point(4.0,4.0))])) 44 | val Point(c,d) = Point(7.0,8.0) 45 | in 46 | if real_equal(a,c) andalso real_equal(b,d) 47 | then (print "eval_prog with 'a' in environment is working properly\n") 48 | else (print "eval_prog with 'a' in environment is not working properly\n") 49 | end; 50 | 51 | 52 | (* With Variable Shadowing *) 53 | let 54 | val Point(a,b) = (eval_prog (Shift(3.0,4.0,Var "a"), [("a",Point(4.0,4.0)),("a",Point(1.0,1.0))])) 55 | val Point(c,d) = Point(7.0,8.0) 56 | in 57 | if real_equal(a,c) andalso real_equal(b,d) 58 | then (print "eval_prog with shadowing 'a' in environment is working properly\n") 59 | else (print "eval_prog with shadowing 'a' in environment is not working properly\n") 60 | end; 61 | -------------------------------------------------------------------------------- /ML-Book.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/ML-Book.pdf -------------------------------------------------------------------------------- /courses.cs.washington.edu:courses:cse341:13sp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/courses.cs.washington.edu:courses:cse341:13sp.pdf -------------------------------------------------------------------------------- /hw1/hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/hw1/hw1.pdf -------------------------------------------------------------------------------- /hw1/johnson_hw1.sml: -------------------------------------------------------------------------------- 1 | fun is_older(d1: int*int*int, d2: int*int*int) = 2 | if (#1 d1) < (#1 d2) 3 | then true 4 | else if (#1 d1) = (#1 d2) andalso (#2 d1) < (#2 d2) 5 | then true 6 | else if (#2 d1) = (#2 d2) andalso (#3 d1) < (#3 d2) 7 | then true 8 | else false 9 | 10 | fun number_in_month(ld: (int*int*int) list, m: int) = 11 | if null ld 12 | then 0 13 | else if #2 (hd ld) = m 14 | then 1 + number_in_month(tl ld, m) 15 | else number_in_month(tl ld, m) 16 | 17 | fun number_in_months(ld: (int*int*int) list, lm: int list) = 18 | if null lm 19 | then 0 20 | else number_in_month(ld, hd lm) + number_in_months(ld, tl lm) 21 | 22 | fun dates_in_month(ld: (int*int*int) list, m: int) = 23 | if null ld 24 | then [] 25 | else let val md = (hd ld) 26 | in if #2 md = m 27 | then md::dates_in_month(tl ld, m) 28 | else dates_in_month(tl ld, m) 29 | end 30 | 31 | fun dates_in_months(ld: (int*int*int) list, lm: int list) = 32 | if null lm 33 | then [] 34 | else dates_in_month(ld, hd lm) @ dates_in_months(ld, tl lm) 35 | 36 | fun get_nth(ls: string list, n: int) = 37 | if n = 1 38 | then hd ls 39 | else get_nth(tl ls, n - 1) 40 | 41 | fun date_to_string(d: int*int*int) = 42 | let val months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 43 | val year = Int.toString(#1 d) 44 | val month = #2 d 45 | val day = " " ^ Int.toString(#3 d) ^ ", " 46 | in get_nth(months, month) ^ day ^ year 47 | end 48 | 49 | fun number_before_reaching_sum(sum: int, l: int list) = 50 | let fun summation(s: int, c: int, l: int list) = 51 | if s >= sum 52 | then c 53 | else summation(s + hd l, c + 1, tl l) 54 | in summation(0, ~1, l) 55 | end 56 | 57 | fun what_month(d: int) = 58 | let val months = [31,28,31,30,31,30,31,31,30,31,30,31] 59 | in number_before_reaching_sum(d, months) + 1 60 | end 61 | 62 | fun month_range(day1: int, day2: int) = 63 | if day1 > day2 64 | then [] 65 | else let fun range(from: int, to: int) = 66 | if from = to 67 | then [to] 68 | else from::range(from + 1, to) 69 | in range(what_month(day1), what_month(day2)) 70 | end 71 | 72 | fun oldest(l: (int*int*int) list) = 73 | if null l 74 | then NONE 75 | else let val max = oldest(tl l) 76 | in if max = NONE 77 | then SOME (hd l) 78 | else if is_older(hd l, valOf max) 79 | then SOME (hd l) 80 | else max 81 | end 82 | 83 | fun oldest_test(l: int list) = 84 | if null l 85 | then NONE 86 | else let val max = oldest_test(tl l) 87 | in if max = NONE 88 | then SOME (hd l) 89 | else if hd l < valOf max 90 | then SOME (hd l) 91 | else max 92 | end; 93 | 94 | fun remove_duplicates(l: int list) = 95 | let fun find(el: int, l: int list) = 96 | if null l 97 | then false 98 | else if el = hd l 99 | then true 100 | else find(el, tl l) 101 | in 102 | if null l 103 | then [] 104 | else if find(hd l, tl l) 105 | then remove_duplicates(tl l) 106 | else (hd l)::remove_duplicates(tl l) 107 | end 108 | 109 | fun number_in_months_challenge(ld: (int*int*int) list, lm: int list) = 110 | number_in_months(ld, remove_duplicates(lm)) 111 | 112 | fun dates_in_months_challenge(ld: (int*int*int) list, lm: int list) = 113 | dates_in_months(ld, remove_duplicates(lm)) 114 | 115 | fun reasonable_date(d: int*int*int) = 116 | let 117 | val year = #1 d 118 | val month = #2 d 119 | val day = #3 d 120 | val is_leapyear = year mod 400 = 0 orelse (year mod 4 = 0 andalso year mod 100 <> 0) 121 | val is_reasonable_year = year > 0 122 | val is_reasonable_month = month > 0 andalso month < 13 123 | val get_months = 124 | if is_leapyear 125 | then [31,29,31,30,31,30,31,31,30,31,30,31] 126 | else [31,28,31,30,31,30,31,31,30,31,30,31] 127 | fun get_max_days_of_month(ml: int list, m: int) = 128 | if m = 1 orelse not is_reasonable_month (*important bug fix. if invalid months are inputted then uncaught exception even though get_max_days_of_month should not get evaluated as it should get short circuited at failure of is_reasonable_month conjunction*) 129 | then hd ml 130 | else get_max_days_of_month(tl ml, m - 1) 131 | val is_reasonable_day = day > 0 andalso day <= get_max_days_of_month(get_months, month)) 132 | in is_reasonable_year andalso is_reasonable_month andalso is_reasonable_day 133 | end; 134 | 135 | use "johnson_hw1_test.sml"; 136 | -------------------------------------------------------------------------------- /hw2/hw2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/hw2/hw2.pdf -------------------------------------------------------------------------------- /hw2/hw2provided.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | 11 | (* you may assume that Num is always used with values 2, 3, ..., 10 12 | though it will not really come up *) 13 | datatype suit = Clubs | Diamonds | Hearts | Spades 14 | datatype rank = Jack | Queen | King | Ace | Num of int 15 | type card = suit * rank 16 | 17 | datatype color = Red | Black 18 | datatype move = Discard of card | Draw 19 | 20 | exception IllegalMove 21 | 22 | (* put your solutions for problem 2 here *) 23 | fg 24 | -------------------------------------------------------------------------------- /hw2/hw2provided.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | 11 | (* you may assume that Num is always used with values 2, 3, ..., 10 12 | though it will not really come up *) 13 | datatype suit = Clubs | Diamonds | Hearts | Spades 14 | datatype rank = Jack | Queen | King | Ace | Num of int 15 | type card = suit * rank 16 | 17 | datatype color = Red | Black 18 | datatype move = Discard of card | Draw 19 | 20 | exception IllegalMove 21 | 22 | (* put your solutions for problem 2 here *) 23 | -------------------------------------------------------------------------------- /hw2/hw2providedTests.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Tests *) 2 | 3 | (* These are just two tests for problem 2; you will want more. 4 | 5 | Naturally these tests and your tests will use bindings defined 6 | in your solution, in particular the officiate function, 7 | so they will not type-check if officiate is not defined. 8 | *) 9 | 10 | fun provided_test1 () = (* correct behavior: raise IllegalMove *) 11 | let val cards = [(Clubs,Jack),(Spades,Num(8))] 12 | val moves = [Draw,Discard(Hearts,Jack)] 13 | in 14 | officiate(cards,moves,42) 15 | end 16 | 17 | fun provided_test2 () = (* correct behavior: return 3 *) 18 | let val cards = [(Clubs,Ace),(Spades,Ace),(Clubs,Ace),(Spades,Ace)] 19 | val moves = [Draw,Draw,Draw,Draw,Draw] 20 | in 21 | officiate(cards,moves,42) 22 | end 23 | -------------------------------------------------------------------------------- /hw2/johnson_hw2.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | fun all_except_option(s, sl) = 11 | let fun helper(l) = 12 | case l of 13 | [] => [] 14 | | x::xs' => if same_string(s,x) then helper(xs') else x::helper(xs') 15 | in 16 | case sl of 17 | [] => NONE 18 | | _ => if helper(sl) = sl then NONE else SOME(helper(sl)) 19 | end 20 | 21 | fun get_substitutions1(sl,s) = 22 | case sl of 23 | [] => [] 24 | | x::xs' => case all_except_option(s, x) of 25 | NONE => get_substitutions1(xs',s) 26 | | SOME l => l @ get_substitutions1(xs',s) 27 | 28 | fun get_substitutions2(sl,s) = 29 | let fun helper(li, acc) = 30 | case li of 31 | [] => acc 32 | | x::xs' => case all_except_option(s,x) of 33 | NONE => helper(xs',acc) 34 | | SOME l => helper(xs',l @ acc) 35 | in helper(sl,[]) 36 | end 37 | 38 | fun similar_names(sl,{first,middle,last}) = 39 | let fun helper(li) = 40 | case li of 41 | [] => [] 42 | | x::xs' => {first=x,last=last, middle=middle}::helper(xs') 43 | in {first=first,last=last, middle=middle}::helper(get_substitutions1(sl, first)) 44 | end 45 | 46 | (* you may assume that Num is always used with values 2, 3, ..., 10 47 | though it will not really come up *) 48 | datatype suit = Clubs | Diamonds | Hearts | Spades 49 | datatype rank = Jack | Queen | King | Ace | Num of int 50 | type card = suit * rank 51 | 52 | datatype color = Red | Black 53 | datatype move = Discard of card | Draw 54 | 55 | exception IllegalMove 56 | 57 | (* put your solutions for problem 2 here *) 58 | fun card_color(suit,rank) = 59 | case suit of 60 | Clubs => Black 61 | | Spades => Black 62 | | _ => Red 63 | 64 | fun card_value(suit,rank) = 65 | case rank of 66 | Ace => 11 67 | | Num x => x 68 | | _ => 10 69 | 70 | fun remove_card(cs,c,e) = 71 | case cs of 72 | [] => raise e 73 | | x::xs' => if x = c then xs' else x::remove_card(xs',c,e) 74 | 75 | fun all_same_color(cs) = 76 | case cs of 77 | [] => true 78 | | x::[] => true 79 | | x::xs'::[] => card_color(x) = card_color(xs') 80 | | x::xs'::xs'' => if card_color(x) = card_color(xs') then all_same_color(xs'::xs'') else false 81 | 82 | fun sum_cards(cs) = 83 | let fun helper(cl, acc) = 84 | case cl of 85 | [] => acc 86 | | x::xs' => helper(xs', card_value(x) + acc) 87 | in helper(cs,0) 88 | end 89 | 90 | fun score(cs,g) = 91 | let val divider = if all_same_color(cs) then 2 else 1 92 | val sum = sum_cards(cs) 93 | val prescore = if sum > g then 3 * (sum - g) else g - sum 94 | in prescore div divider 95 | end 96 | 97 | fun officiate(cds,moves,i) = 98 | let fun helper(c,m,h) = 99 | case (c,m,sum_cards(h) > i) of 100 | (_,_,true) => score(h,i) 101 | | (_,[],false) => score(h,i) 102 | | (_,(Discard crd)::xs',false) => helper(c,xs',remove_card(h,crd,IllegalMove)) 103 | | ([],(Draw)::xs',false) => score(h,i) 104 | | (x::xs',(Draw)::ys',false) => helper(xs',ys',x::h) 105 | in helper(cds,moves,[]) 106 | end; 107 | 108 | fun replace_one_ace(cs) = 109 | case cs of 110 | [] => [] 111 | | (c, Ace)::xs' => (c,Num(1))::xs' 112 | | card::xs' => card::replace_one_ace(xs') 113 | 114 | fun replace_one_ace_move(cs) = 115 | case cs of 116 | [] => [] 117 | | Discard(c, Ace)::xs' => Discard(c,Num(1))::xs' 118 | | card::xs' => card::replace_one_ace_move(xs') 119 | 120 | fun least_of(ls) = 121 | case ls of 122 | [] => 0 123 | | x::[] => x 124 | | x::xs' => let val min = least_of(xs') 125 | in if min < x 126 | then min 127 | else x 128 | end; 129 | 130 | fun score_challenge(cs,g) = 131 | let fun container(cs) = 132 | let val replaced = replace_one_ace(cs) 133 | in if cs = replaced 134 | then [score(cs,g)] 135 | else score(cs,g)::container(replaced) 136 | end 137 | in least_of(container(cs)) 138 | end; 139 | 140 | fun officiate_challenge(cds,moves,i) = 141 | let fun container(cs, moves) = 142 | let val replaced = replace_one_ace(cs) 143 | val repl_moves = replace_one_ace_move(moves) 144 | in if cs = replaced 145 | then [officiate(cs,moves,i)] 146 | else officiate(cs,moves,i)::container(replaced, repl_moves) 147 | end 148 | in least_of(container(cds, moves)) 149 | end; 150 | 151 | fun careful_player(cs,g) = 152 | let fun research_discard(held, new_card, total_value) = 153 | case held of 154 | [] => NONE 155 | | card::xs' => if total_value - card_value(card) + card_value(new_card) = g 156 | then SOME([Discard(card),Draw]) 157 | else research_discard(xs', new_card, total_value) 158 | 159 | fun helper(cs,held,moves) = 160 | case (cs, score(held,g) = 0) of 161 | (_,true) => moves 162 | | ([],false) => moves 163 | | (card::xs',false) => if sum_cards(held) <= g - 11 164 | then helper(xs',held@[card],moves@[Draw]) 165 | else case research_discard(held, card, sum_cards(held)) of 166 | NONE => moves 167 | | SOME(move) => helper(xs',held@[card],moves@move) 168 | in helper(cs,[],[]) 169 | end; 170 | 171 | use "johnson_hw2_test.sml"; 172 | 173 | (* 174 | f([(Clubs,Ace),(Hearts,Num(5)),(Spades,Ace),(Clubs,Jack)],22); 175 | *) 176 | -------------------------------------------------------------------------------- /hw2/johnson_hw2.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Code *) 2 | 3 | (* if you use this function to compare two strings (returns true if the same 4 | string), then you avoid several of the functions in problem 1 having 5 | polymorphic types that may be confusing *) 6 | fun same_string(s1 : string, s2 : string) = 7 | s1 = s2 8 | 9 | (* put your solutions for problem 1 here *) 10 | fun all_except_option(s, sl) = 11 | case sl of 12 | [] => NONE 13 | | x::[] => SOME [] 14 | | x::xs' => if same_string(s,x) then SOME xs' else all_except_option(s, xs') 15 | 16 | (* you may assume that Num is always used with values 2, 3, ..., 10 17 | though it will not really come up *) 18 | datatype suit = Clubs | Diamonds | Hearts | Spades 19 | datatype rank = Jack | Queen | King | Ace | Num of int 20 | type card = suit * rank 21 | 22 | datatype color = Red | Black 23 | datatype move = Discard of card | Draw 24 | 25 | exception IllegalMove 26 | 27 | (* put your solutions for problem 2 here *) 28 | 29 | fun officiate(c,m,i) = i; 30 | use "johnson_hw2_test.sml"; 31 | -------------------------------------------------------------------------------- /hw2/johnson_hw2_test.sml~: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW2 Provided Tests *) 2 | 3 | val s1 = "CIvuNCJacBmzmN" 4 | val s2 = "xJeC3Oe6nJV4Cg" 5 | val s3 = "7IK3QAz2kNRCLs" 6 | val s4 = "i2oqTL6VTvJLUy" 7 | val s5 = "PMA3UfR5oYARjA" 8 | val s6 = "qoA5sTMLzuDRmb" 9 | val s7 = "MTmxbwXCSt5YLB" 10 | val s8 = "pp7htnOE3ag9Lq" 11 | val s9 = "urpWliQU08Gnk8" 12 | val s10 = "He1lIb6X0iu8IX" 13 | 14 | val sl1 = [s1,s2,s3,s4,s5,s6,s7,s8,s9,s10] 15 | val sl2 = ""::sl1 16 | val sl3 = [] 17 | val sl4 = [""] 18 | val sl5 = ["1"]; 19 | all_except_option("", sl2) = SOME sl1; 20 | all_except_option(s1,sl1) = SOME (tl sl1); 21 | all_except_option(s1,sl2) = SOME ""::(tl sl1); 22 | all_except_option(s2,sl3) = NONE; 23 | all_except_option("",sl1) = SOME sl1; 24 | all_except_option("",sl4) = SOME []; 25 | all_except_option("random",sl4) = SOME sl4; 26 | all_except_option("1",sl5) = SOME []; 27 | 28 | (* These are just two tests for problem 2; you will want more. 29 | 30 | Naturally these tests and your tests will use bindings defined 31 | in your solution, in particular the officiate function, 32 | so they will not type-check if officiate is not defined. 33 | *) 34 | 35 | fun provided_test1 () = (* correct behavior: raise IllegalMove *) 36 | let val cards = [(Clubs,Jack),(Spades,Num(8))] 37 | val moves = [Draw,Discard(Hearts,Jack)] 38 | in 39 | officiate(cards,moves,42) 40 | end 41 | 42 | fun provided_test2 () = (* correct behavior: return 3 *) 43 | let val cards = [(Clubs,Ace),(Spades,Ace),(Clubs,Ace),(Spades,Ace)] 44 | val moves = [Draw,Draw,Draw,Draw,Draw] 45 | in 46 | officiate(cards,moves,42) 47 | end 48 | -------------------------------------------------------------------------------- /hw3/hw3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/hw3/hw3.pdf -------------------------------------------------------------------------------- /hw3/hw3provided.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** for the challenge problem only ****) 30 | 31 | datatype typ = Anything 32 | | UnitT 33 | | IntT 34 | | TupleT of typ list 35 | | Datatype of string 36 | 37 | (**** you can put all your code here ****) 38 | -------------------------------------------------------------------------------- /hw3/johnson_hw3.sml: -------------------------------------------------------------------------------- 1 | (* Dan Grossman, CSE341 Spring 2013, HW3 Provided Code *) 2 | 3 | exception NoAnswer 4 | 5 | datatype pattern = Wildcard 6 | | Variable of string 7 | | UnitP 8 | | ConstP of int 9 | | TupleP of pattern list 10 | | ConstructorP of string * pattern 11 | 12 | datatype valu = Const of int 13 | | Unit 14 | | Tuple of valu list 15 | | Constructor of string * valu 16 | 17 | fun g f1 f2 p = 18 | let 19 | val r = g f1 f2 20 | in 21 | case p of 22 | Wildcard => f1 () 23 | | Variable x => f2 x 24 | | TupleP ps => List.foldl (fn (p,i) => (r p) + i) 0 ps 25 | | ConstructorP(_,p) => r p 26 | | _ => 0 27 | end 28 | 29 | (**** for the challenge problem only ****) 30 | 31 | datatype typ = Anything 32 | | UnitT 33 | | IntT 34 | | TupleT of typ list 35 | | Datatype of string 36 | 37 | (**** you can put all your code here ****) 38 | fun only_capitals(ls) = List.filter (fn(x) => case size x of 39 | 0 => false 40 | | _ => Char.isUpper(String.sub(x,0))) ls 41 | 42 | fun longest_string1(ls) = foldl(fn(x,y) => if size x > size y then x else y) "" ls 43 | fun longest_string2(ls) = foldl(fn(x,y) => if size x >= size y then x else y) "" ls 44 | 45 | fun longest_string_helper f ls = List.foldl(fn(x,acc) => if f(size x, size acc) then x else acc) "" ls 46 | val longest_string3 = longest_string_helper (fn(x,y) => x > y) 47 | val longest_string4 = longest_string_helper (fn(x,y) => x >= y) 48 | 49 | val longest_capitalized = longest_string1 o only_capitals 50 | 51 | (*Important note for function below: 52 | fun rev_string(s: string) = implode o rev o explode s 53 | will not work 54 | 55 | http://stackoverflow.com/questions/12729640/why-is-there-type-mismatch-of-operator-and-operand 56 | *) 57 | fun rev_string(s) = (implode o rev o explode) s 58 | 59 | 60 | fun first_answer f ls = 61 | case ls of 62 | [] => raise NoAnswer 63 | | x::xs' => case f(x) of 64 | SOME v => v 65 | | NONE => first_answer f xs' 66 | 67 | fun all_answers f ls = 68 | let fun accumulator(ls,acc) = 69 | case ls of 70 | [] => SOME acc 71 | | x::xs' => case f(x) of 72 | SOME v => accumulator(xs',acc@v) 73 | | NONE => NONE 74 | in accumulator(ls,[]) 75 | end 76 | 77 | 78 | 79 | (* 80 | 9.a The function g takes three parameters in curried format, the first two are functions and the last one is a variable binding of type pattern. The function g eventually evaluates to type int. 81 | In essence, the function g computes the given pattern p according to the criteria of the two functions evaluating to a single value of type int. 82 | *) 83 | 84 | fun count_wildcards p = g (fn(_) => 1) (fn(_) => 0) p 85 | 86 | fun count_wild_and_variable_lengths p = g (fn(_) => 1) (fn(s) => String.size(s)) p 87 | fun count_some_var (s,p) = g (fn(_) => 0) (fn(v) => if v = s then 1 else 0) p 88 | 89 | fun check_pat p = 90 | let fun extract_Var p = 91 | case p of 92 | Variable s => [s] 93 | | TupleP ls => List.foldl(fn(p,acc) => acc@(extract_Var p)) [] ls 94 | | ConstructorP(_,p) => extract_Var p 95 | | _ => [] 96 | fun no_duplicates ls = 97 | case ls of 98 | [] => false 99 | | x::[] => true 100 | | x::xs' => if (List.exists (fn(y) => y = x) (xs')) then false else no_duplicates(xs') 101 | in no_duplicates(extract_Var p) 102 | end 103 | 104 | fun match(v,p) = 105 | case(v,p) of 106 | (_,Wildcard) => SOME [] 107 | | (v,Variable s) => SOME [(s,v)] 108 | | (Unit,UnitP) => SOME [] 109 | | (Const _, ConstP _) => SOME [] 110 | | (Tuple(vs), TupleP(ps)) => if List.length vs = List.length ps 111 | then all_answers (match) (ListPair.zip(vs,ps)) 112 | else NONE 113 | | (Constructor(s2,v),ConstructorP(s1,p)) => if s1 = s2 114 | then match(v,p) 115 | else NONE 116 | | _ => NONE 117 | 118 | fun first_match v lp = SOME (first_answer (match) (List.map(fn(x) => (v,x)) lp)) 119 | handle NoAnswer => NONE 120 | -------------------------------------------------------------------------------- /hw3/unit3notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/hw3/unit3notes.pdf -------------------------------------------------------------------------------- /test.sml: -------------------------------------------------------------------------------- 1 | val x = 3; 2 | fun pow(x, y) = 3 | if y=0 4 | then 1 5 | else x * pow(x, y - 1); 6 | 7 | fun cube (x) = 8 | pow(x, 3); 9 | 10 | fun swap(pr: int*bool) = 11 | (#2 pr, #1 pr); 12 | 13 | fun sum_two_pairs(pr1: int*int, pr2: int*int) = 14 | (#1 pr1 + #1 pr2, #2 pr1 + #2 pr2); 15 | 16 | fun summation(pr1: int*int, pr2: int*int) = 17 | (#1 pr1) + (#2 pr1) + (#1 pr2) + (#2 pr2); 18 | 19 | fun div_mod(x: int, y: int) = 20 | (x div y, x mod y); 21 | 22 | fun sort_pair(pr: int*int) = 23 | if (#1 pr) < (#2 pr) 24 | then pr 25 | else ((#2 pr), (#1 pr)); 26 | 27 | fun sum_list (xs: int list) = 28 | if null xs 29 | then 0 30 | else hd(xs) + sum_list(tl xs); 31 | 32 | fun count_down (x: int) = 33 | if x = 0 34 | then [] 35 | else x::count_down(x - 1); 36 | 37 | fun append(xs, ys: int list) = 38 | if null xs 39 | then ys 40 | else (hd xs)::append(tl xs, ys); 41 | 42 | fun sum_pair_list(xs: (int*int) list) = 43 | if null xs 44 | then 0 45 | else (#1 (hd xs)) + (#2 (hd xs)) + sum_pair_list(tl xs); 46 | 47 | fun firsts (xs: (int*int) list) = 48 | if null xs 49 | then [] 50 | else (#1 (hd xs))::firsts(tl xs); 51 | 52 | fun seconds (xs: (int*int) list) = 53 | if null xs 54 | then [] 55 | else (#2 (hd xs))::seconds(tl xs); 56 | 57 | val result = seconds([(1, 2), (3, 4), (5, 6)]); 58 | 59 | fun count_up (x: int) = 60 | let fun count(from: int) = 61 | if from > x 62 | then [] 63 | else from::count(from + 1) 64 | in 65 | count 1 66 | end 67 | val test_count = count_up(10); 68 | 69 | fun good_max(xs: int list) = 70 | if null xs 71 | then 0 72 | else if null (tl xs) 73 | then hd xs 74 | else let val temp = good_max(tl xs) 75 | in 76 | if hd xs > temp 77 | then hd xs 78 | else temp 79 | end 80 | 81 | val test_max = good_max([1,2,3,4,5,100,5,33,7]); 82 | -------------------------------------------------------------------------------- /unit1notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ajwah/Programming-Languages/ff36463b2762b92cfb1830e92f49c33b29477511/unit1notes.pdf --------------------------------------------------------------------------------