Created
August 5, 2012 08:32
-
-
Save tototoshi/3262935 to your computer and use it in GitHub Desktop.
start_scalaz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._, Scalaz._ | |
case class User(id: String, pass: String) | |
object Main extends App { | |
implicit object userShow extends Show[User] { | |
def show(u: User) = u.toString.toList | |
} | |
implicit object userEq extends Equal[User] { | |
def equal(u1: User, u2: User) = u1 == u2 | |
} | |
def user(m: Map[String, String]): Option[User] = { | |
(m.get("id") |@| m.get("pass")) { (id, pass) => | |
User(id, pass) | |
} | |
} | |
user(Map("id" -> "takahashi", "pass" -> "hogehoge")) assert_=== Some(User("takahashi", "hogehoge")) | |
user(Map.empty[String, String]) assert_=== None | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._, Scalaz._ | |
import java.util.Date | |
object JavaUtilDateOrdering { | |
implicit object javaUtilDateOrdering extends Order[Date] { | |
def order(d1: Date, d2: Date) = { | |
if (d1.getTime == d2.getTime) { | |
Ordering.EQ | |
} else if (d1.getTime < d2.getTime) { | |
Ordering.LT | |
} else { | |
Ordering.GT | |
} | |
} | |
} | |
} | |
case class Student(name: String, grade: Int, birthday: Date) | |
object Student { | |
implicit object StudentOrdering extends Order[Student] { | |
def order(s1: Student, s2: Student) = | |
s1.grade ?|? s2.grade |+| s1.birthday ?|? s2.birthday | |
} | |
implicit object StudentShow extends Show[Student] { | |
def show(s: Student) = s.toString.toList | |
} | |
} | |
object Main extends App { | |
val format = new java.text.SimpleDateFormat("yyyy MM dd") | |
val akari = Student("akari", 1, format.parse("1995 07 24")) | |
val kyoko = Student("kyoko", 2, format.parse("1995 03 28")) | |
val yui = Student("yui", 2, format.parse("1994 04 22")) | |
val chinatsu = Student("chinatsu", 1, format.parse("1995 11 06")) | |
List(akari, kyoko, yui, chinatsu).sorted(Order[Student].toScalaOrdering) assert_=== List(akari, chinatsu, yui, kyoko) | |
println(List(akari, kyoko, yui, chinatsu).sorted(Order[Student].toScalaOrdering).mkString("\n")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment