如何用F#语言中的输入模式执行特定的功能

时间:2016-11-11 03:01:10

标签: f# functional-programming f#-interactive f#-3.0 f#-data

我对F#有点新意,并试用了一个简单的计算器应用程序。我接受用户的输入,我想根据输入执行特定的功能。 现在,每当我从用户那里获取任何输入时,程序就从上到下执行。我希望它只执行与输入匹配的特定功能。就像输入是6那样,应该执行scienceFun()的主体。现在它执行所有功能。请帮助,我有点卡在这一个! 代码是

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 个答案:

答案 0 :(得分:2)

您应该将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()