
So instead of val sorted3 = fn x => fn y => fn z => … or fun sorted3 x = fny => fn z => …, can just write fun sorted3 x y z = x >=y andalso y >= x.In general, fun f p1 p2 p3 …= e, means fun f p1 = fn p2 => fn p3 => … => e.Syntactic sugar, part 2 valsorted3 = fnx=> fny=> fnz=> z >= yandalsoy >= x valt1 = ((sorted3 7) 9) 11 Different than tupling caller and callee must use same technique CSE341: Programming Languages.Callers can just think “multi-argument function with spaces instead of a tuple expression”.So instead of ((sorted3 7) 9) 11, can just write sorted3 7 9 11.Syntactic sugar, part 1 valsorted3 = fnx=> fny=> fnz=> z >= yandalsoy >= x valt1 = ((sorted3 7) 9) 11 Calling that closure with 11returns true CSE341: Programming Languages.Calling that closure with 9 returns a closure with:.
#SORTED3 SUNRISE CODE#
Code fny => fnz => z >= yandalsoy >= x.Calling (sorted3 7)returns a closure with:.Called “currying” after famous logician Haskell Curry CSE341: Programming LanguagesĮxample valsorted3 = fnx=> fny=> fnz=> z >= yandalsoy >= x valt1 = ((sorted3 7) 9) 11.Another way: Take one argument and return a function that takes another argument and….Previously encoded n arguments via one n-tuple.Recall every ML function takes exactly one argument.As is often the case with higher-order functions, the types hint at what the function does ('a -> 'b option) * ('a -> 'b) -> 'a -> 'b fun backup1 (f,g) = fnx=> case f x of NONE => g x |SOME y => y CSE341: Programming Languages.This one is very popular (and predefined) in F# infix|> funx |> f=f x funsqrt_of_absi= i|> abs |> omInt |> Math.sqrt CSE341: Programming Languages.“square root of the conversion to real of absolute value” “Pipelines” of functions are common in functional programming and many programmers prefer left-to-right.“take absolute value, convert to real, and take square root”.Left-to-right or right-to-left valsqrt_of_abs= As in math, function composition is “right to left” Example (third version best): fun compose (f,g) =fnx => f (g x) funsqrt_of_absi=Math.sqrt(omInt(abs i)) funsqrt_of_absi=()i valsqrt_of_abs= CSE341: Programming Languages.ML standard library provides this as infix operator o.Type ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) but the REPL prints something equivalent.Creates a closure that “remembers” what f and gare bound to.Implementing an ADT with a record of functions (optional) CSE341: Programming LanguagesĬombine functions Canonical example is function composition:.Callbacks (e.g., in reactive programming).Currying (multi-arg functions and partial application).Pass functions with private data to iterators: Done.Now what is it good for A partial but wide-ranging list:.We know the rule for lexical scope and function closures.CSE341: Programming LanguagesLecture 9Function-Closure Idioms Dan Grossman Winter 2013
