Commit a34eca04 authored by Haochen Xie's avatar Haochen Xie

add started/First.scala

parent 134089a0
package name.haochenxie.fpscala.started
import java.text.DateFormat
import java.util.Locale
/**
* Created by haochen on 2017/01/22.
*/
object HelloWorld {
def main(args: Array[String]) {
println("Hello world!")
println(10.-(4))
}
}
object FrenchDate {
def main(args: Array[String]) {
val now = new java.util.Date()
val df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRENCH)
println(df format now)
}
}
object Timer {
def oncePerSecond(cb: () => Unit): Unit = {
while (true) { cb(); Thread.sleep(1000) }
}
def timeFlies() = println("time flies like an arrow..")
def main(args: Array[String]) {
// oncePerSecond(timeFlies)
oncePerSecond(() => println("meow"))
}
}
case class Complex(re: Double, im: Double) {
def translate(reDelta: Double, imDelta: Double) =
Complex(re + reDelta, im + imDelta)
override def toString = s"%s${ if (im >= 0) "+" else "" }%s".format(re, im)
}
abstract class Exp
case class Sum(l: Exp, r: Exp) extends Exp {
override def toString: String = s"($l+$r)"
}
case class Var(id: String) extends Exp {
override def toString: String = id.toString
}
case class Const(v: Int) extends Exp {
override def toString: String = v.toString
}
object Exp {
type Environment = String => Int
def eval(env: Environment)(exp: Exp): Int = {
val e: Exp => Int = eval(env)
exp match {
case Sum(l, r) => e(l) + e(r)
case Var(id) => env(id)
case Const(v) => v
}
}
def derive(x: String)(exp: Exp): Exp = {
val d: Exp => Exp = derive(x)
exp match {
case Sum(l, r) => Sum(d(l), d(r))
case Var(id) if id == x => Const(1)
case _ => Const(0)
}
}
}
trait Ord[A] {
def < (that: A): Boolean
def <=(that: A): Boolean = (this < that) || (this == that)
def > (that: A): Boolean = !(this <= that)
def >=(that: A): Boolean = !(this < that)
}
case class Date(year: Int, month: Int, day: Int) extends Ord[Date] {
override def <(that: Date): Boolean =
year < that.year || month < that.month || day < that.day
}
object FirstScratchPad {
def main(args: Array[String]) {
// println(Complex(10, 20))
// println(Complex(10, -3))
// val exp: Sum = Sum(Var("x"), Const(10))
// println(exp)
// println(Exp.eval({ case "x" => 3 })(exp))
// // println(Exp.eval({ case "y" => 3 })(exp))
// println(Exp.derive("x")(exp))
// println(Exp.derive("y")(exp))
val dateA = Date(1995, 3, 10)
val dateB = Date(1995, 6, 20)
println(dateA)
println(dateB)
println((dateA < dateB))
}
}
package name.haochenxie.fpscala.started
/**
* Created by haochen on 2017/01/22.
*/
object HelloWorld {
def main(args: Array[String]) {
println("Hello world!")
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment