Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. case class Person(name: String, age: Int)
  2.  
  3.  
  4. def searchForJohn(personList:List[Person]):List[Person] = {
  5.  
  6. personList match {
  7. case Nil => Nil
  8. case p :: ps if(p.name.map(_.toLower).startsWith("john") ) => p :: searchForJohn(ps)
  9. case _ :: ps => searchForJohn(ps)
  10. }
  11. }
  12.  
  13. val people = List(Person("Jon Stewart", 56), Person("Zorro", 100), Person("John Stuart Mill", 66), Person("David Hume", 65), Person("David Bowie", 69))
  14. searchForJohn(people)
  15.  
  16. //if we look at the majority of this function it documents
  17. //how to traverse the structure of a list
  18. //not about what we're deciding to return
  19. //what if we could encapsulate that into a function and pass it
  20. //to our function
  21.  
  22. //functions in scala are first order, they can be
  23. // treated as values and passed around into functions
  24. // and returned from functions
  25.  
  26. def searchFor(predicate: Person => Boolean)(personList:List[Person]):List[Person] = {
  27. personList match {
  28. case Nil => Nil
  29. case p :: ps if(predicate(p)) => p :: searchFor(predicate)(ps)
  30. case _ :: ps => searchFor(predicate)(ps)
  31. }
  32. }
  33.  
  34. val searchForJohn2: List[Person] => List[Person] = searchFor((p:Person) => p.name.map(_.toLower).startsWith("john"))(_)
  35. searchForJohn2(people)
  36.  
  37. //We've curried the function above, we've partially applied it
  38. // in order to create a new function we can use as many times as we want
  39.  
  40. val searchForDavid: List[Person] => List[Person] = searchFor((p:Person) => p.name.map(_.toLower).startsWith("david"))(_)
  41. searchForDavid(people)
  42.  
  43. //HOF lets us concentrate on each concern in the right place
  44. //SearchFor deals with walking the data structure
  45. //The predicate we pass in is the logic for deciding if we
  46. // want to keep it
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement