オブジェクト指向・関数型エクササイズ ref: http://qiita.com/ababup1192/items/2250a7025188d8ff3dd5
newtype Coin = Coin Int deriving (Show)
doubleCoin :: Coin -> Coin
doubleCoin (Coin x) = Coin (x * 2)
-- 単なる、整数は渡せない。
*Main> doubleCoin 1
<interactive>:3:12:
No instance for (Num Coin) arising from the literal ‘1’
In the first argument of ‘doubleCoin’, namely ‘1’
In the expression: doubleCoin 1
In an equation for ‘it’: it = doubleCoin 1
-- Coin型として、渡す。
*Main> doubleCoin (Coin 8)
Coin 16
def evenFilter(x: Int): Either[String, Int] = if(x % 2 == 0) Right(x) else Left("奇数でした。")
def printEven(x: Int): Unit = {
evenFilter(x) match {
case Right(x) => println(x)
case Left(err) => System.err.println(err)
}
}
// 三項演算子としての、if-else式
def evenFilter(x: Int): Option[Int] = if(x % 2 == 0) Some(x) else None
def printEven(x: Int): Unit = {
evenFilter(x).foreach(println)
}
public static void endMe(){
if(status == DONE){
doSomething();
return;
}
// その他のコード ...
}
public static void endMe() {
if(status == DONE){
doSomething();
}else{
// その他のコード ...
}
}
// Scalaは、元々パラダイムが関数型のため、Listオブジェクトは、高階関数を扱うメソッドが備わっている。
// そのため記述が楽。
val doubleList = list.map(_ * 2)
val evenList 0 list.filter(_ % 2 == 0)
List<Integer> doubleList = list.stream().map(x -> x * 2).collect(Collectors.toList());
List<Integer> eventList = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
// 配列の要素を二倍する。
List<Integer> doubleList = new ArrayList<>();
for(int element: list){
doubleList.add(element * 2);
}
// 特定の要素を取り除く。
List<Integer> evenList = new ArrayList<>();
for(int element: list){
if(element % 2 == 0){
evenList.add(element);
}
}
sealed trait Coin
def Coin(value: Int): Int @@ Coin = Tag[Int, Coin](value)
def doubleCoin(coin: Int @@ Coin): Int @@ Coin = Coin(scalaz.Tag.unsubst[Int, Id, Coin](coin) * 2)
# 三項演算子ならば、大抵の言語が適用可
dobleOver10 = x > 10 ? x * 2 : x
// 式が評価されて値を返す。
1 + 1 // => 2
// ifも式として評価されて値を返す。
if(true) 1 else 0 // => 1