Skip to content

Instantly share code, notes, and snippets.

@kenbot
Created June 18, 2014 15:21
Show Gist options
  • Save kenbot/bae43f81c5f24f1b370b to your computer and use it in GitHub Desktop.
Save kenbot/bae43f81c5f24f1b370b to your computer and use it in GitHub Desktop.
package fpexample
import scala.util.Try
import scala.io.Source
case class Record[K,+A](key: K, fields: A) {
def map[B](f: A => B): Record[K, B] = Record(key, f(fields))
}
object DataMunger {
val file = """
|1,banana,3.5566
|2,apple,66.0
|3,cumquat,-0.3
|4,durian,88.722
|5,pear,77.99
""".stripMargin
def swap[K,A,B](record: Record[K, (A,B)]): Record[K, (B,A)] =
record.map(_.swap)
def marketingBlurb(name: String, price: Double): String =
s"Wow! Such $name. For you, only $price doglars"
def addMarketingBlurb[K](record: Record[K, (String, Double)]): Record[K, (String,Double,String)] =
record.map {
case (name, price) => (name, price, marketingBlurb(name, price))
}
type ID = Int
type OurRecordFormat = Record[ID, (String, Double)]
def readRecord(line: String): Option[OurRecordFormat] = {
def splitLine(line: String): List[String] = line.split(",").toList
def coerceCells(cells: List[String]): Option[OurRecordFormat] = {
def coerceInt(str: String): Option[Int] = Try(str.toInt).toOption
def coerceDouble(str: String): Option[Double] = Try(str.toDouble).toOption
def createRecord(keyStr: String, a: String, bStr: String) = for {
key <- coerceInt(keyStr)
b <- coerceDouble(bStr)
} yield Record(key, (a,b))
cells match {
case keyStr :: a :: bStr :: Nil => createRecord(keyStr, a, bStr)
case _ => None
}
}
coerceCells(splitLine(line))
}
def main(args: Array[String]): Unit = {
val validRecords = Source.fromString(file).getLines.flatMap(readRecord).toList
val swapped = validRecords map swap
val withMarketingBlurb = validRecords map addMarketingBlurb
println(s"\nSwapped: \n${swapped.mkString(",\n")}")
println(s"\nWith marketing blurb: \n${withMarketingBlurb.mkString(",\n")}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment