'&$%CSE 341:Programming LanguagesWinter 2005Lecture 3— Let bindings, options, and benefits of no mutationCSE341 Winter 2005, Lecture 3 1'&$%Let bindingsMotivation: Functions without local variables can be poor style and/orreally inefficient.Syntax: let b1 b2 ... bn in e end where each bi is a binding.Typing rules: Type-check each bi and e in context including previousbindings. Type of whole expression is type of e.Evaluation rules: Evaluate each bi and e in environment includingprevious bindings. Value of whole expression is result of evaluating e.Elegant design worth repeating:• Let-expressions can appe ar anywhere an expression can.• Let-expressions can have any kind of binding.– Local functions can refer to any bindings in scope.CSE341 Winter 2005, Lecture 3 2'&$%More than styleExercise: hand-evaluate bad_max and good_max for lists [1,2][1,2,3], and [3,2,1].CSE341 Winter 2005, Lecture 3 3'&$%Summary and general patternMajor progress: recursive functions, pairs, lists, let-expressionsEach has a syntax, typing rules, evaluation rules.Functions, pairs, and lists are very different, but we can describe themin the same way:• How do you create values? (function definition, pair expressions,empty-list and ::)• How do you use values? (function application, #1 and #2, null,hd, and tl)This (and conditionals) is enough for your homework though:• andalso and orelse help• You need options (next slide)• Soon: much better ways to use pairs and lists (pattern-matching)CSE341 Winter 2005, Lecture 3 4'&$%Options“Options are like lists that can have at most one element.”• Create a t option with NONE or SOME e where e has type t.• Use a t option with isSome and valOfWhy not just use (more ge neral) lists? An interesting style trade-off:• Options better express purpose, enforce invariants on callers,maybe faster.• But cannot use functions for lists already written.CSE341 Winter 2005, Lecture 3 5'&$%You want to ch ange something?There is no way to mutate (assign to) a binding, pair component, orlist element.How could the lack of a feature make programming easier?In this case:• Amount of sharing is indistinguishable– Aliasing irrelevant to correctness!• Bindings are invariant across function application– Mutation breaks compositional reasoning, a (the?) intellectualtool of engineeringCSE341 Winter 2005, Lecture 3
View Full Document