zhanyong wan, yale university september, 2001

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

Upload: tobias-forbes

Post on 31-Dec-2015

25 views

Category:

Documents


3 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Zhanyong Wan,  Yale University September, 2001

Having Having FunFun with with FunctionsFunctions

How you can use functions to:How you can use functions to:write interactive animation,write interactive animation,control robots, andcontrol robots, andcompose music.compose music.

Zhanyong Wan, Yale UniversitySeptember, 2001

Acknowledgement: Part of the slides provided by Paul Hudak

Page 2: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 2

RoadmapRoadmap

Programming languages research at Yale

• Introduction to Haskell

• Domain specific languages

• FRP

• Haskore

• Conclusions and video

Page 3: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 3

Alan Perlis’ Epigrams in ProgrammingAlan 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.

Page 4: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 4

PL Research at YalePL 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.

Page 5: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 5

Having Fun at YaleHaving Fun at Yale

• John Peterson

– Rock climbing

– Skiing

– Kayaking

• Paul Hudak

– Music

– Soccer coaching

– Skiing

– Rock climbing

– Kayaking

audio

Page 6: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 6

RoadmapRoadmap

• Programming languages research at Yale

Introduction to Haskell

• Domain specific languages

• FRP

• Haskore

• Conclusions and video

Page 7: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 7

Haskell by ExamplesHaskell by Examples

• Higher-order functions– Functions are first-class values

– Currying• max :: (Int,Int) Intmax (x,y) = if x > y then x else y

max(5,6) 6

• max :: Int (Int Int)max x y = if x > y then x else y

max 5 6 6

• m5 :: Int Intm5 = max 5 <==> m5 y = if 5 > y then 5 else y

m5 4 5m5 6 6

In C, this would be int max(int,

int);

Page 8: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 8

Haskell by ExamplesHaskell by Examples

• Recursion– sum [] = 0

sum (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

Page 9: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 9

Haskell by ExamplesHaskell 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 : …

Page 10: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 10

Haskell by ExamplesHaskell 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

Page 11: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 11

Haskell by ExamplesHaskell by Examples

• Advanced type systems

– Polymorphic• zipWith :: a,b,c. (abc) [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]

Page 12: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 12

RoadmapRoadmap

• Programming languages research at Yale

• Introduction to Haskell

Domain specific languages

• FRP

• Haskore

• Conclusions and video

Page 13: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 13

Animation in a General-Purpose Animation in a General-Purpose LanguageLanguage• 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!

Page 14: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 14

We Need Domain SpecificityWe 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

Page 15: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC

• 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

Advantages of DSL ApproachAdvantages of DSL Approach

Contribute to higherprogrammer productivity

Dominant cost in large SW systems

Verification, transform- ation, optimization

Helps bridge gap betweendeveloper and user

These are the same arguments in favor of any high-level language. But in addition:

Page 16: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 16

The Bottom LineThe Bottom Line

To

tal S

W C

ost

C1

C2

Software Life-Cycle

Start-up Costs DSL-based

Methodology

Conventional Methodology

Page 17: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 17

DSL’s Allow Faster PrototypingDSL’s Allow Faster Prototyping

specify specify

test

design

build test

design

build

With DSLWithout DSL

Using the “Spiral Model” of Software Development

Page 18: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 18

RoadmapRoadmap

• Programming languages research at Yale

• Introduction to Haskell

• Domain specific languages

FRP

• Haskore

• Conclusions and video

Page 19: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 19

Reactive ProgrammingReactive 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

environ-

ment

environ-

ment

reactivesystem

stimuli responses

Page 20: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 20

Functional Reactive ProgrammingFunctional 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

time

behavior

time

event

Page 21: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 21

What Is FRP Good for?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”

moveXY (sin time) 0 charlotte

charlotte = importBitmap “charlotte.bmp”

Page 22: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 22

Basic ConceptsBasic Concepts

• Behaviors (Behavior a)– Reactive, continuous-time-varying values

time :: Behavior Timemouse :: 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

Page 23: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 23

BehaviorsBehaviors

• Timetime :: Behavior Time

• Inputmouse :: Behavior Point2

• Integrationintegral :: Behavior Double

-> Behavior Double

(integral time)

• Constant behaviorslift0 :: a -> Behavior a

(lift0 5)

Page 24: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 24

LiftingLifting

• Static value -> behaviorlift0 :: a -> Behavior a

lift1 :: (a -> b) -> Behavior a -> Behavior b

lift2 :: (a -> b -> c)

-> Behavior a -> Behavior b -> Behavior c

...

• Exampleslift1 sin time

sin time

lift2 (+) (lift0 1) (lift1 sin time)

1 + sin time

time

time

Page 25: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 25

Simple BehaviorsSimple Behaviors

• Hello, world!hello :: Behavior Picture

hello = text $ lift0 "Hello, world!"

main1 = animate hello

• Interaction: mouse-followingmain2 = animate $ moveTo mouse hello

• Timemain3 = animate $ text $ lift1 show time

demo

Page 26: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 26

Geometry in FRPGeometry 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

Page 27: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 27

Spatial TransformationsSpatial Transformations

• Spatial transformations -- dancing ballball :: 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

demo

Page 28: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 28

Spatial CompositionSpatial Composition

• Spatial composition -- dancing ball & textmain5 = animate $ moveTo mouse $

moveXY (wiggle 4) (waggle 4) ball `over`

moveXY (wiggle 7) (waggle 3) hello

demo

Page 29: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 29

Recursive BehaviorsRecursive 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

v

-kf v

ks dpo

d

pm

Page 30: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 30

Recursive Behaviors (cont’d)Recursive Behaviors (cont’d)

• FRP Codemain6 = 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

demo

Page 31: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 31

SwitchingSwitching

• Switching of behaviorscolor :: Behavior Color

color = red `till` lbp -=> blue

mouseBall :: Behavior Picture

mouseBall = moveTo mouse $ stretch 0.5 circle

main7 = animate $ withColor color mouseBall

• Recursive switchingcycle3 c1 c2 c3 = c1 `till` lbp

-=> cycle3 c2 c3 c1

main8 = animate $

withColor (cycle3 red green blue) mouseBall

demo

Page 32: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 32

Paddle Ball in 17 LinesPaddle Ball in 17 Lines• paddleball vel = walls `over` paddle `over` pball vel

walls = 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` right

paddle = 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

video

Page 33: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 33

Crouching Robots, Hidden CameraCrouching Robots, Hidden Camera

• RoboCup

– Team controllers written in FRP

– Embedded robot controllers written in C(our goal: use FRP instead)

camera

radioradio

Team Bcontroller

Team Acontroller

Page 34: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 34

A Point-tracking Control SystemA Point-tracking Control System

• Input

– xd, yd, d: desired position & heading

– x, y, : actual position & heading

• Output

– u: forward speed

– v: rotational speed

(xd,yd)

(x,y)

d

uv

Page 35: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 35

A Point-tracking SystemA Point-tracking Systemu = 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)

θ/θsin

θ/)θcos1(

θcos)(θsin)(

θsin)(θcos)(

θsinθcos

θθθ

θθ

2

1

2

1

22112

11

d

d

dd

dd

ddddd

d

d

d

ur

ur

yyxxz

yyxxz

yxu

zrzrkv

zkuu

video

Page 36: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 36

RoadmapRoadmap

• Programming languages research at Yale

• Introduction to Haskell

• Domain specific languages

• FRP

Haskore

• Conclusions and video

Page 37: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 37

HaskoreHaskore

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.

Page 38: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 38

Basic Haskore StructureBasic 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 | Bstype Octave = Int

data Music = Note Pitch Dur -- a note | Rest Dur -- a rest | Music :+: Music -- sequential composition | Music :=: Music -- parallel composition | Tempo Int Int Music -- scale the tempo | Trans Int Music -- transposition | Instr IName Music -- instrument label

type Dur = Float -- in whole notestype IName = Stringtype PName = String

Page 39: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 39

GloveGlove

by Tom Makucevich

with help from Paul Hudak

Composed using Haskore, a Haskell DSL,and rendered using csound.

Page 40: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 40

RoadmapRoadmap

• Programming languages research at Yale

• Introduction to Haskell

• Domain specific languages

• FRP

• Haskore

Conclusions and video

Page 41: Zhanyong Wan,  Yale University September, 2001

September, 2001USTC 41

ConclusionsConclusions

• 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)

video