FSharp やってみた2

その 2。

add という関数を定義して、引数を渡して評価してみる:

> let add x y =
-   x + y;;
val add : x:int -> y:int -> int

> add 2 2;;
val it : int = 4

関数のボディ部分を折ってるけど、インデントしないと Warning が出るので注意。

あと、終了する時は:

> exit 0;;

か:

> #q;;

でできる。

アノテーション

フレーズを渡したら、leet 語っぽく返してくれる関数を定義してみよう:

> let toHackerTalk phrase =                          
-   phrase.Replace( 't', '7' ).Replace( 'o', '0' );; 

    phrase.Replace( 't', '7' ).Replace( 'o', '0' );;
  --^^^^^^^^^^^^^^
/home/rihine/workspace/hello-fsharp/stdin(4,3): error FS0072: Lookup on object of
indeterminate type based on information prior to this program point. A type annotation 
may be needed prior to this program point to constrain the type of the object. 
This may allow the lookup to be resolved.

エラーになった。
どうやら、引数 phraseobject っぽく解釈されてるものの、object には当然 Replace() なんてメソッドはないわけで、 そんなもん無いよって言ってるらしい。

アノテーションを付けてみるといいらしい:

> let toHackerTalk (phrase:string) =                
-   phrase.Replace( 't', '7' ).Replace( 'o', '0' );;
val toHackerTalk : phrase:string -> string

関数は実際、値

ソースコードをファイルに書いて実行することにする。
引数を 4 倍する関数を定義する:

// quadruple.fsx
let quadruple x =
  let double x =
    x * 2

  double ( double x );;

printfn "%d" (quadruple 4);;

関数の中で関数を定義できる。という感じ。

普通にファイル名を指定するだけで実行してくれる:

% fsharpi ./quadruple.fsx
16

関数を引数に取る高階関数を使うコード:

// chrisTest.fsx
let chrisTest test =
  test "Chris"
;;

let isMe x =
  if x = "Chris" then
    "it is Chris!"
  else
    "it's someone else"
;;
    
printfn "%A" (chrisTest isMe);;

ラムダ関数

前の add 関数はラムダ式で書くとこう書ける:

> let add = (fun x y -> x + y);;
val add : x:int -> y:int -> int

その2:

> let twoTest test =
-   test 2;;
val twoTest : test:(int -> 'a) -> 'a

> twoTest (fun x -> x < 0);;
val it : bool = false

参照