LoginSignup
1
0

The Rust Programming Languageの数当てゲームをFsharpで実装してみる

Posted at
open System

printfn "Guess the number!"

let rnd = System.Random()
let secretNumber = rnd.Next(1, 101)

let tryParseInt (input: string) =
    match Int32.TryParse(input) with
    | (true, i) -> Some i
    | _ -> None

let rec loop () =
    printfn "Please input your guess."
    let input = stdin.ReadLine()
    printfn "You entered %s" input
    let parsedInput = tryParseInt input

    let result =
        match parsedInput with
        | Some i when i = secretNumber -> "You win!"
        | Some i when i < secretNumber -> "Too low!"
        | Some i when i > secretNumber -> "Too high!"
        | _ -> "Invalid input!"

    printfn "%s" result

    match result with
    | "You win!" -> ()
    | _ -> loop ()

loop ()

matchの結果をresultで取得して、You win!かどうかを判定しているのが微妙。
本来は型に変えて、その型に応じて出し分けたり処理を変更したりしたほうが良いでしょうね。win low highの文字が変わったら対応できなくなるので、ユニオン型にして処理したほうが良いか。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0