2016-11-11 85 views
1

我對F#有點新鮮,並嘗試使用簡單的計算器應用程序。我從用戶那裏接受輸入,並且我想要根據輸入執行特定的功能。 現在,無論何時我接受用戶的任何輸入,程序都會執行從上到下的操作。我希望它只執行與輸入匹配的特定功能。如果輸入是6,那麼scientificFun()的主體應該被執行。現在它執行所有功能。請幫助,我有點卡在這一個! 該代碼是如何使用F#語言的輸入模式執行特定功能

open System 

let mutable ok = true 
while ok do 
    Console.WriteLine("Choose a operation:\n1.Addition\n2.Substraction\n3.Multiplication\n4.Division\n5.Modulo\n6.Scientific") 
    let input= Console.ReadLine() 

    let add = 
     Console.WriteLine("Ok, how many numbers?") 
     let mutable count = int32(Console.ReadLine()) 
     let numberArray = Array.create count 0.0 
     for i in 0 .. numberArray.Length - 1 do 
      let no = float(Console.ReadLine()) 
      Array.set numberArray i no  
    Array.sum numberArray 
    let sub x y = x - y 
    let mul x y = x * y 
    let div x y = x/y 
    let MOD x y = x % y 
    let scientificFun() = 
     printfn("1. Exponential") 
    match input with 
    | "1" -> printfn("The Result is: %f") (add) 
    | "6" -> (scientificFun()) 
    | _-> printfn("Choose between 1 and 6") 
    Console.WriteLine("Would you like to use the calculator again? y/n") 
    let ans = Console.ReadLine() 
    if ans = "n" then 
     ok <- false 
    else Console.Clear() 
+1

你是新來的F#或一般編程? –

+1

新的f#或功能範式 –

+0

感興趣:[REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) –

回答

3

應該定義add作爲功能:let add() =let add inputNumbers =

否則下面僅該簡化版本執行對應於輸入號碼的功能:

open System 

[<EntryPoint>] 
let main argv = 


    // define your functions 
    let hellofun() = 
     printfn "%A" "hello" 

    let worldfun() = 
     printfn "%A" "world" 


    let mutable cont = true 
    let run() = // set up the while loop 
     while cont do 
     printfn "%A" "\nChoose an operation:\n 1 hellofunc\n 2 worldfunc\n 3 exit" 
     let input = Console.ReadLine() // get the input 
     match input with // pattern match on the input to call the correct function 
     | "1" -> hellofun() 
     | "2" -> worldfun() 
     | "3" -> cont <- false;() 
     | _ -> failwith "Unknown input" 

    run() // kick-off the loop 
    0 

[<EntryPoint>] let main argv =是隻有在編譯它時纔有必要。否則,請執行run()