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

How to execute specific functions with input pattern in F# language

我对 F# 有点陌生,正在尝试一个简单的计算器应用程序。我从用户那里获取输入,我希望根据输入执行特定的功能。 现在,每当我接受用户的任何输入时,程序都会从​​上到下执行。我希望它只执行与输入匹配的特定功能。就像如果输入是 6 那么应该执行 scientificFun() 的主体。现在它执行所有功能。请帮忙,我有点卡在这个问题上了! 密码是

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()

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