https://coderwall.com/p/4l73-a/scala-fold-foldleft-and-foldright
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}
val fooList = Foo("Joe Smith", 25, 'male) :: Foo("Susan Jones", 43, 'female) :: Foo("Fred Flintstone", 37, 'male) :: Nil
val stringList = fooList.foldLeft(List[String]()) { (z, f) =>
val title = f.sex match {
case 'male => "Mr."
case 'female => "Ms."
}
z :+ s"$title ${f.name}, ${f.age}"
}
class Foo(val name: String, val age: Int, val sex: Symbol)
object Foo {
def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
}
val fooList = Foo("Joe Smith", 25, 'male) :: Foo("Susan Jones", 43, 'female) :: Foo("Fred Flintstone", 37, 'male) :: Nil
val stringList = fooList.foldLeft(List[String]()) { (z, f) =>
val title = f.sex match {
case 'male => "Mr."
case 'female => "Ms."
}
z :+ s"$title ${f.name}, ${f.age}"
}
scala> class Foo(val name: String, val age: Int, val sex: Symbol)
defined class Foo
warning: previously defined object Foo is not a companion to class Foo.
Companions must be defined together; you may wish to use :paste mode for this.
scala>
scala> object Foo {
| def apply(name: String, age: Int, sex: Symbol) = new Foo(name, age, sex)
| }
defined object Foo
warning: previously defined class Foo is not a companion to object Foo.
Companions must be defined together; you may wish to use :paste mode for this.
scala>
scala> val fooList = Foo("Joe Smith", 25, 'male) :: Foo("Susan Jones", 43, 'female) :: Foo("Fred Flintstone", 37, 'male) :: Nil
fooList: List[Foo] = List(Foo@52d3542b, Foo@282afe91, Foo@7b1e1c25)
scala>
scala> val stringList = fooList.foldLeft(List[String]()) { (z, f) =>
| val title = f.sex match {
| case 'male => "Mr."
| case 'female => "Ms."
| }
| z :+ s"$title ${f.name}, ${f.age}"
| }
stringList: List[String] = List(Mr. Joe Smith, 25, Ms. Susan Jones, 43, Mr. Fred Flintstone, 37)
No comments:
Post a Comment