Created
October 5, 2015 14:59
-
-
Save to4iki/ca6ac64b368de2d4b596 to your computer and use it in GitHub Desktop.
Algebraic Data Types
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
/** | |
* 代数的データ型 | |
*/ | |
object AlgebraicDataTypes extends App { | |
import Bool._ | |
println(True.id) // 0 | |
println(Bool(0)) // True | |
println(Bool.withName("True")) // True | |
def offset(p1: Point, p2: Point): Point = Point(p1.x + p2.x, p1.y + p2.y) | |
def get[A](r: Result[A]): String = r match { | |
case Ok(x) => "ok" | |
case Err => "error" | |
} | |
println(get(Ok("a"))) | |
println(get(Err)) | |
println(Ok("a").isOK) // true | |
//-- | |
// http://modegramming.blogspot.jp/2012/07/30-3-on-scala.html | |
case class Person(name: String, age: Int) | |
val a: Product = Person("a",1) | |
val b: Product = ("a",1) | |
} | |
/** | |
* 列挙型: 種類を区別するための型 | |
* | |
* http://www.ne.jp/asahi/hishidama/home/tech/scala/enumeration.html | |
* Bool: 型(型構築子) / True: constructor(データ構築子) | |
*/ | |
object Bool extends Enumeration { | |
type Bool = Value | |
val True, False = Value | |
} | |
/** | |
* 直積型: 内部に値を持つ型(構造体/tuple) | |
*/ | |
sealed trait Coordinates | |
case class Point(x: Int, y: Int) extends Coordinates | |
/** | |
* 直和型: 列挙型にフィールドを付加する事で、複数の直積型を定義したもの | |
* https://doc.rust-lang.org/std/result/ | |
*/ | |
sealed trait Result[+A] { | |
def isOK: Boolean | |
} | |
case class Ok[A](x: A) extends Result[A] { | |
override def isOK: Boolean = true | |
} | |
case object Err extends Result[Nothing] { | |
override def isOK: Boolean = false | |
} | |
/** | |
* 直積型や直和型のフィールドに名前を付けることができます。これをレコード構文と呼ぶ | |
*/ | |
sealed trait Data | |
case class User(name: String, age: Int) extends Data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment