1 / 41

Zhanyong Wan, Yale University September, 2001

Having Fun with Functions How you can use functions to: write interactive animation, control robots, and compose music. Zhanyong Wan, Yale University September, 2001 Acknowledgement: Part of the slides provided by Paul Hudak. Roadmap.  Programming languages research at Yale

Download Presentation

Zhanyong Wan, Yale University September, 2001

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Having Fun with FunctionsHow you can use functions to: write interactive animation, control robots, and compose music. Zhanyong Wan, Yale UniversitySeptember, 2001 Acknowledgement: Part of the slides provided by Paul Hudak

  2. Roadmap •  Programming languages research at Yale • Introduction to Haskell • Domain specific languages • FRP • Haskore • Conclusions and video USTC

  3. Alan Perlis’ Epigrams in Programming • A programming language is low level when its programs require attention to the irrelevant. • If a listener nods his head when you're explaining your program, wake him up. • Optimization hinders evolution. • Once you understand how to write a program get someone else to write it. • The use of a program to prove the 4-color theorem will not change mathematics - it merely demonstrates that the theorem, a challenge for a century, is probably not important to mathematics. • There are two ways to write error-free programs; only the third one works. • A language that doesn't affect the way you think about programming, is not worth knowing. USTC

  4. PL Research at Yale • Faculty members (a partial list): • Paul Hudak: functional programming (Haskell), domain specific languages, language theory. • John Peterson: functional programming (Haskell), domain specific languages, compilation • Zhong Shao: functional programming (ML), type theory, compilation techniques, proof-carrying code. • Carsten Schuermann: logical frameworks, theorem proving, type theory, functional programming. USTC

  5. Having Fun at Yale audio • John Peterson • Rock climbing • Skiing • Kayaking • Paul Hudak • Music • Soccer coaching • Skiing • Rock climbing • Kayaking USTC

  6. Roadmap • Programming languages research at Yale •  Introduction to Haskell • Domain specific languages • FRP • Haskore • Conclusions and video USTC

  7. Haskell by Examples • Higher-order functions • Functions are first-class values • Currying • max :: (Int,Int)  Intmax (x,y) = if x > y then x else ymax(5,6)  6 • max :: Int  (Int  Int)max x y = if x > y then x else ymax 5 6  6 • m5 :: Int  Intm5 = max 5 <==> m5 y = if 5 > y then 5 else ym5 4  5m5 6  6 In C, this would be int max(int, int); USTC

  8. Haskell by Examples • Recursion • sum [] = 0sum (x:xs) = x +sum xs • prod [] = 1prod (x:xs) = x *prod xs • Higher-order functions improve modularization • Modularization is the key to successful programming! • fold f a [] = afold f a (x:xs) = f x (fold f a xs) • sum = fold (+) 0 • prod = fold (*) 1 • allTrue = fold (&&) True • anyTrue = fold (||) False USTC

  9. Haskell by Examples • Lazy evaluation • Call-by-need • f x y = if x > 0 then x else y… f e1 e2 … • Infinite data structures • ones = 1 : ones  1 : 1 : 1 : 1 : 1 : … • numsFrom n = n : numsFrom (n+1) n : n+1 : n+2 : n+3 : … • squares = map (^2) (numsFrom 0) 0 : 1 : 4 : 9 : 16 : 25 : 36 : … • take 5 squares  [0, 1, 4, 9, 16] • fib = 1 : 1 : zipWith (+) fib (tail fib) 1 : 1 : 2 : 3 : 5 : 8 : 13 : … (+) 1 : 2 : 3 : 5 : 8 : 13 : 21 : … -------------------------------------1 : 1 : 2 : 3 : 5 : 8 : 13 : 21 : 34 : … USTC

  10. Haskell by Examples • Lazy evaluation • Another powerful tool for improving modularity • sort xs = … take n xs = … smallest n x = take n (sort x) • Only practical for lazy languages • Need-driven: no unnecessary computation • No large intermediate data structure USTC

  11. Haskell by Examples • Advanced type systems • Polymorphic • zipWith :: a,b,c.(abc)  [a]  [b]  [c] • Type inference • zipWith f [] _ = []zipWith f _ [] = []zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys • a  [b]  c  [d] refine a  [b]  [e]  [d] refine (b  e  d)  [b]  [e]  [d]rename (a  b  c)  [a]  [b]  [c] USTC

  12. Roadmap • Programming languages research at Yale • Introduction to Haskell •  Domain specific languages • FRP • Haskore • Conclusions and video USTC

  13. Animation in a General-Purpose Language • Sketch of the code (taken from Elliott’s Fran manual): allocate and initialize window, various drawing surfaces and bitmaps repeat until quit: get time ( t ) clear back buffer for each sprite (back to front): compute position, scale, etc. at t draw to back buffer flip back buffer to the screen deallocate bitmaps, drawing surfaces, window • Lots of tedious, low-level code that you have to write yourself • There is a better way! USTC

  14. We Need Domain Specificity • A domain-specific language (or DSL) is a language that precisely captures a domain semantics; no more, and no less. • Examples • SQL, UNIX shells, Perl, Prolog • FRP, Haskore USTC

  15. Advantages of DSL Approach • Programs in the target domain are: • more concise • quicker to write • easier to maintain • easier to reason about • can often be written by non-programmers Contribute to higher programmer productivity Dominant cost in large SW systems Verification, transform- ation, optimization These are the same arguments in favor of any high-level language. But in addition: Helps bridge gap between developer and user

  16. The Bottom Line Conventional Total SW Cost Methodology C2 Start - up DSL - based Costs Methodology C1 Software Life-Cycle USTC

  17. DSL’s Allow Faster Prototyping Using the “Spiral Model” of Software Development specify design specify design build test build test Without DSL With DSL USTC

  18. Roadmap • Programming languages research at Yale • Introduction to Haskell • Domain specific languages •  FRP • Haskore • Conclusions and video USTC

  19. reactive system responses stimuli environ-ment Reactive Programming • Reactive systems • Continually react to stimuli • Environment cannot wait – system must respond quickly • Run forever • Examples • Computer animation • GUI • Robotics • Vision • Control systems • Real-time systems USTC

  20. behavior time time event Functional Reactive Programming • Functional Reactive Programming (FRP) • Focuses on model instead of presentation • Continuous time domain • Discrete time domain • Recursion + higher-order functions • Originally embedded in Haskell • Continuous/discrete signals • Behaviors: values varying over time • Events: discrete occurrences • Reactivity: b1 ‘until‘ ev -=> b2 • Combinators: until, switch, when, integral, etc USTC

  21. What Is FRP Good for? • Applications of FRP • Fran [Elliott and Hudak] Interactive animation • Frob [Peterson, Hager, Hudak and Elliott] Robotics • FVision [Reid, Peterson, Hudak and Hager] Vision • Frappé[Courtney] Java • FranTk [Sage], Fruit [Courtney] GUI moveXY (sin time) 0 charlotte charlotte = importBitmap “charlotte.bmp” USTC

  22. Basic Concepts • Behaviors (Behavior a) • Reactive, continuous-time-varying values time :: Behavior Time mouse :: Behavior Point2 • Events (Event a) • Streams of discrete event occurrences lbp :: Event () • Switching b1 `till` lbp -=> b2 • Combinators • Behaviors and events are both first-class • Passed as arguments • Returned by functions • Composed using combinators USTC

  23. Behaviors • Time time :: Behavior Time • Input mouse :: Behavior Point2 • Integration integral :: Behavior Double -> Behavior Double (integral time) • Constant behaviors lift0 :: a -> Behavior a (lift0 5) USTC

  24. Lifting • Static value -> behavior lift0 :: a -> Behavior a lift1 :: (a -> b) -> Behavior a -> Behavior b lift2 :: (a -> b -> c) -> Behavior a -> Behavior b -> Behavior c ... • Examples lift1 sin time  sin time lift2 (+) (lift0 1) (lift1 sin time)  1 + sin time time time USTC

  25. Simple Behaviors demo • Hello, world! hello :: Behavior Picture hello = text $ lift0 "Hello, world!" main1 = animate hello • Interaction: mouse-following main2 = animate $ moveTo mouse hello • Time main3 = animate $ text $ lift1showtime USTC

  26. Geometry in FRP • 2-D • Points • Vectors • Common shapes • Circle, line, polygon, arc, and etc • Affine transformations • Rotation • Translation • Reflection • Scaling • Shear • Composition of the above • 3-D as well USTC

  27. Spatial Transformations demo • Spatial transformations -- dancing ball ball :: Behavior Picture ball = withColor red $ stretch 0.1 circle wiggle, waggle :: Behavior Double -> Behavior Double wiggle omega = sin (omega*time) waggle omega = cos (omega*time) main4 om1 om2 = animate $ moveXY (wiggle om1) (waggle om2) $ moveTo mouse ball USTC

  28. Spatial Composition demo • Spatial composition -- dancing ball & text main5 = animate $ moveTo mouse $ moveXY (wiggle 4) (waggle 4) ball `over` moveXY (wiggle 7) (waggle 3) hello USTC

  29. Recursive Behaviors • Damped motion of a mass dragged with a spring • Integral equations • Recursive d = pm – po a = ksd – kfv v =  a dt po =  v dt d pm v po ks d -kf v USTC

  30. Recursive Behaviors (cont’d) demo • FRP Code main6 = animate $ moveTo po ball `over` withColor blue (line mouseB po) where ks = 1 kf = 0.8 d = mouse .-. po a = ks *^ d – kf *^ v v = integral a po = vector2ToPoint2 $ integral v • Declarative • Concise • Recursive d = pm – po a = ksd – kfv v =  a dt po =  v dt USTC

  31. Switching demo • Switching of behaviors color :: Behavior Color color = red `till` lbp -=> blue mouseBall :: Behavior Picture mouseBall = moveTo mouse $ stretch 0.5 circle main7 = animate $ withColor color mouseBall • Recursive switching cycle3 c1 c2 c3 = c1 `till` lbp -=> cycle3 c2 c3 c1 main8 = animate $ withColor (cycle3 red green blue) mouseBall USTC

  32. Paddle Ball in 17 Lines video • paddleball vel = walls `over` paddle `over` pball velwalls = let upper = paint blue (translate ( 0,1.7) (rec 4.4 0.05))             left  = paint blue (translate (-2.2,0) (rec 0.05 3.4))            right = paint blue (translate ( 2.2,0) (rec 0.05 3.4))         in upper `over` left `over` rightpaddle = paint red (translate (fst mouse, -1.7) (rec 0.5 0.05))pball vel =  let xvel    = vel `stepAccum` xbounce ->> negate      xpos    = integral xvel      xbounce = when (xpos >* 2 ||* xpos <* -2)      yvel    = vel `stepAccum` ybounce ->> negate      ypos    = integral yvel      ybounce = when (ypos >* 1.5                   ||* ypos `between` (-2.0,-1.5) &&*                      fst mouse `between` (xpos-0.25,xpos+0.25))  in paint yellow (translate (xpos, ypos) (ell 0.2 0.2))x `between` (a,b) = x >* a &&* x <* b USTC

  33. Crouching Robots, Hidden Camera • RoboCup • Team controllers written in FRP • Embedded robot controllers written in C(our goal: use FRP instead) camera Team A controller Team B controller radio radio USTC

  34. A Point-tracking Control System • Input • xd, yd, d: desired position & heading • x, y, : actual position & heading • Output • u: forward speed • v: rotational speed d (xd,yd) u  v (x,y) USTC

  35. A Point-tracking System video u = u_d - k1 * z1 v = k2 * derivativeB theta_d – dTheta - r1 * z1 - r2 * z2 dTheta = lift1 normalizeAngle $ theta - theta_d u_d = derivativeB x_d * cos theta_d + derivativeB y_d * sin theta_d z1 = (x – x_d) * cos theta + (y – y_d) * sin theta z2 = (x – x_d) * sin theta – (y – y_d) * cos theta r1 = ifZ (abs dTheta <* 0.01) 0 (u_d*(1 - cos dTheta)/dTheta) r2 = ifZ (abs dTheta <* 0.01) (-u_d) (-u_d * sin dTheta / dTheta) USTC

  36. Roadmap • Programming languages research at Yale • Introduction to Haskell • Domain specific languages • FRP •  Haskore • Conclusions and video USTC

  37. Haskore Motivation: Traditional music notation has many limitations: • Unable to express a composer’s intentions. • Biased toward music that is humanly performable. • Unable to express notions of algorithmic composition.Haskore (“Haskell” + “Score”) is a library of Haskellfunctions and datatypes for composing music. USTC

  38. Basic Haskore Structure type Pitch = (PitchClass, Octave) data PitchClass = Cf | C | Cs | Df | D | Ds | Ef | E | Es | Ff | F | Fs | Gf | G | Gs | Af | A | As | Bf | B | Bs type Octave = Int data Music = NotePitchDur -- a note | RestDur -- a rest | Music:+:Music -- sequential composition | Music:=:Music -- parallel composition | TempoIntIntMusic -- scale the tempo | TransIntMusic -- transposition | InstrINameMusic -- instrument label type Dur = Float -- in whole notes type IName = String type PName = String USTC

  39. Gloveby Tom Makucevichwith help from Paul HudakComposed using Haskore, a Haskell DSL,and rendered using csound. USTC

  40. Roadmap • Programming languages research at Yale • Introduction to Haskell • Domain specific languages • FRP • Haskore •  Conclusions and video USTC

  41. Conclusions video • Haskell has changed the way many people think about programming. It is worth knowing! • Functional programming community have some good ideas. Let’s start using them! • Functional programming is fun! • Check out our web-site! • Haskell http://haskell.org/ • FRP http://haskell.org/frp/ • Haskore http://haskell.org/haskore/ • Hugs http://haskell.org/hugs/ • Life at Yale is fun! (See the video) USTC

More Related