DOC PREVIEW
Stanford CS 94SI - For Expressions

This preview shows page 1-2-3-24-25-26-27-49-50-51 out of 51 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 51 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

For expressionsJulien WetterwaldCS 94SIList<Person> persons = ...for (int i = 0; i < persons.size(); i++) { Person p = persons.at(i); ...}for (Person p : persons) { ...}Iterating in JavaIterating in ScalaList[Person] persons = ...for (p ← persons) ...persons.foreach(p ⇒ ...)FilteringList[Person] persons = ...for (p ← persons if p.age > 20) ...persons.filter(p ⇒ p.age > 20) .foreach(p ⇒ ...)Producing a collectionList[Person] persons = ...for (p ← persons if p.age > 20) yield p.namepersons.filter(p ⇒ p.age > 20) .map(p ⇒ p.name)Nested iterationfor (x ← 1 to 2 y ← 'a' to 'b') yield (x, y)(1 to 2).flatMap(x ⇒ ('a' to 'b').map(y ⇒ (x, y)))Why flatMap?for (x ← 1 to 2 y ← 'a' to 'b') yield (x, y) ⇒ [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] (1 to 2).map(x ⇒ ('a' to 'b').map(y ⇒ (x, y))) ⇒ [[(1, 'a'), (1, 'b')], [(2, 'a'), (2,'b')]]Generalization●Not restricted to lists or any other collections●Rely only on map, filter and flatMap●Iterate over any class implementing these operationsGeneralizationDatabase[Person] persons = ...for (p ← persons if p.age > 20) yield p.namepersons.filter(p ⇒ p.age > 20) .map(p ⇒ p.name)Software CompositionJulien WetterwaldCS 94SICompositionality●Build interesting structures from simple parts●“Glue” building blocks●Reuse and adapt existing parts●Ensure scalability of the methods for constructing the systemsThe Plan1. Write building blocks2. ?3. Profit!The Plan1. Write building blocks2. Use spacesuits3. Profit!Building blocksfunctions E. W. Dijkstra, Structured Programming, 1972.monads P. Wadler, Comprehending Monads, 1990.objects (or modules)software componentsservicesMonadsE. Kow, Of monads and spacesuitshttp://www.loria.fr/~kow/monads/What is a monad?●a way to structure computations●strategy for combining computations into more complex computationsMotivating exampleval a = f(x)if (a == null) { null} else { val b = g(a) if (b == null) null else h(b)}Motivating examplef(x) match { case None ⇒ None case Some(a) ⇒ g(a) match { case None ⇒ None case Some(b) ⇒ h(b) }}Motivating examplef(x) match { case None ⇒ None case Some(a) ⇒ g(a) match { case None ⇒ None case Some(b) ⇒ h(b) }}Motivating examplef(x) then g(a) then h(b)Motivating examplef(x) then g then hMotivating examplef(x)then gthen hThe space station metaphortype a = astronautspace station :: a ⇒ aSpace Lawspace station :: a ⇒ Suit[a]The bind robotdef >>= (suit: Suit[a], f: a ⇒ Suit[a]): Suit[a] = f(extractAstronaut(suit))bind and thenastronautInASpaceSuit>>= spaceStation1>>= spaceStation2>>= spaceStation3bind and thenastronautInASpaceSuit>>= putInSuit(singing(_))>>= putInSuit(dancing(_))>>= putInSuit(farting(_))Kinds of space1) space stations (functions)2) astronauts (inputs)3) space suits (monadic values)4) the bind robot (>>=)5) kind of space (monads)The Option spacedef >>= (suit: Option[a], f: a ⇒ Option[a]): Option[a] = suit match { case None ⇒ None case Some(x) ⇒ f(x) }def >>= (suit: Suit[a], f: a ⇒ Suit[a]): Suit[a] = f(extractAstronaut(suit))The List spacedef >>= (suit: List[a], f: a ⇒ List[a]): List[a] = suit match { case Nil ⇒ Nil case suit ⇒ suit flatMap f }def >>= (suit: Suit[a], f: a ⇒ Suit[a]): Suit[a] = f(extractAstronaut(suit))stationstationWork of the robot in the List spacestationrobotfor notation, againastronautInASpaceSuit>>= spaceStation1>>= spaceStation2>>= spaceStation3for (a1 ← astronautInASpaceSuita2 ← spaceStation1(a1)a3 ← spaceStation2(a2))yield spaceStation3(a3)Why does it work?def >>= (suit: List[a], f: a ⇒ List[a]): List[a] = suit match { case Nil ⇒ Nil case suit ⇒ suit flatMap f }def >>= (suit: List[a], f: a ⇒ List[a]): List[a] = suit flatMap fThus...for (a1 ← astronautInASpaceSuita2 ← spaceStation1(a1))yield spaceStation2(a2)astronautInASpaceSuit>>= spaceStation1>>= spaceStation2astronautInASpaceSuit.flatMap(a1 ⇒ spaceStation1(a1).map(a2 ⇒ spaceStation2(a2)))Space (monad) formulationtrait Monad[m[_]] { val >>=: (m[a], a ⇒ m[a]) ⇒ m[a] val unit: a => m[a]}unit(x) >>= fm >>= unit(m >>= f) >>= g≡ f(x)≡ m≡ m >>= (x ⇒ f(x) >>= g)Space (monad) formulationobject OptionMonad extends Monad[Option] { def >>= (suit: Option[a], f: a ⇒ Option[a]): Option[a] = suit flatMap f def unit(x: a) = Some(x)}Some(x) >>= fm >>= unit(m >>= f) >>= g≡ Some(x) flatMap f≡ m flatMap Some(_)≡ ...≡ f(x)≡ mWhy bother?●Modularity–separate the combination strategy from the actual computations●Flexibility–distill the computational strategy into a single place●Isolation–create imperative-style computational structureThreading partial functionf(x) match { case None ⇒ None case Some(a) ⇒ g(a) match { case None ⇒ None case Some(b) ⇒ h(b) }}Threading partial functionf(x)then gthen hThreading partial functionfor (a ← f(x) b ← g(a)) yield h(b)break;continue;Objects andsoftware componentsM. Odersky, M. Zenger, Scalable Component Abstractions, 2005.Building blocksfunctions E. W. Dijkstra, Structured Programming, 1972.monads P. Wadler, Comprehending Monads, 1990.objects (or modules)software componentsservicesSoftware componentDefines interfaces for providedas well as for required services“Hard link” to required servicetrait Configuration { val password = ...}class Blog { val config: Configuration = new LocalConfiguration def ... { ... = config.password }}Dependency injectionclass Blog { var config: Configuration // dependency // called automagically @Inject def set(myConfig: Configuration) { config = myConfig } def ... { ... = config.password }}Static dependency injectionabstract class Blog { val config: Configuration // dependency def ... { ... = config.password }}val myBlog = new Blog { val config = new LocalConfiguration}Self-typesabstract class Blog { def ... { ... = password; ... } // won't compile}new Blog with LocalConfigurationSelf-typesabstract class Blog { this: Configuration ⇒ def ... { ... = password; ... }}new Blog with Configuration //


View Full Document

Stanford CS 94SI - For Expressions

Download For Expressions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view For Expressions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view For Expressions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?