Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- case class Person(name: String, age: Int)
- def searchForJohn(personList:List[Person]):List[Person] = {
- personList match {
- case Nil => Nil
- case p :: ps if(p.name.map(_.toLower).startsWith("john") ) => p :: searchForJohn(ps)
- case _ :: ps => searchForJohn(ps)
- }
- }
- val people = List(Person("Jon Stewart", 56), Person("Zorro", 100), Person("John Stuart Mill", 66), Person("David Hume", 65), Person("David Bowie", 69))
- searchForJohn(people)
- //if we look at the majority of this function it documents
- //how to traverse the structure of a list
- //not about what we're deciding to return
- //what if we could encapsulate that into a function and pass it
- //to our function
- //functions in scala are first order, they can be
- // treated as values and passed around into functions
- // and returned from functions
- def searchFor(predicate: Person => Boolean)(personList:List[Person]):List[Person] = {
- personList match {
- case Nil => Nil
- case p :: ps if(predicate(p)) => p :: searchFor(predicate)(ps)
- case _ :: ps => searchFor(predicate)(ps)
- }
- }
- val searchForJohn2: List[Person] => List[Person] = searchFor((p:Person) => p.name.map(_.toLower).startsWith("john"))(_)
- searchForJohn2(people)
- //We've curried the function above, we've partially applied it
- // in order to create a new function we can use as many times as we want
- val searchForDavid: List[Person] => List[Person] = searchFor((p:Person) => p.name.map(_.toLower).startsWith("david"))(_)
- searchForDavid(people)
- //HOF lets us concentrate on each concern in the right place
- //SearchFor deals with walking the data structure
- //The predicate we pass in is the logic for deciding if we
- // want to keep it
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement