2016-11-11 38 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()