数字または文字列を返す。

条件によって数字を返したり、文字列を返したりする if 文。(Ruby の例)


$ irb
irb(main):004:0> cnd=true
=> true
irb(main):005:0> if cnd then 1 else "NG" end
=> 1
irb(main):006:0> cnd=false
=> false
irb(main):007:0> if cnd then 1 else "NG" end
=> "NG"

Haskell は型にうるさいのでエラーになる。


Prelude> if True then 100 else "String"

<interactive>:1:13:
No instance for (Num [Char])
arising from the literal `100' at <interactive>:1:13-15
Possible fix: add an instance declaration for (Num [Char])
In the expression: 100
In the expression: if True then 100 else "String"
In the definition of `it': it = if True then 100 else "String"

型を合わせればOK。


Prelude> if True then (show 100) else "String"
"100"
Prelude> if False then (show 100) else "String"
"String"
Prelude> if True then 100 else 200
100

新たに型を定義する。


data Ret = RetCnd Int | RetText String deriving (Eq,Read,Show)

*Main> :load d.hs
[1 of 1] Compiling Main ( d.hs, interpreted )
Ok, modules loaded: Main.
*Main> if True then RetCnd 100 else RetText "String"
RetCnd 100
*Main> if False then RetCnd 100 else RetText "String"
RetText "String"
*Main> :t if False then RetCnd 100 else RetText "String"
if False then RetCnd 100 else RetText "String" :: Ret