我试图在f#中使用两个数组创建一个计算器,一个存储数字,另一个存储运算符。我需要符号数组来模式匹配符号,并根据运算符从数组中获取前两个元素并执行操作并将新数字添加到第二个数组的头部。从数组中取出两个元素并添加它们,然后将它们添加回数组
open System
[<EntryPoint>]
let main argv =
printfn "%A" argv
let Add x y = x + y
let Sub x y = x - y
let Div x y = x * y
let Mul x y = x/y
printfn "1 > Calculator \n2 > Load from txt file"
let chosenIn = Console.ReadLine();
//This is where I need to do the operation and after call the sum function
//again until there's only one element left in the number array
let rec sum num (numArray : int[]) sym (symArray : string[])() =
let rec calc() =
printfn "Enter Sum"
let input = Console.ReadLine()
let intInput = input.Split()
let numArray = [|for num in intInput do
let v , vp = System.Int32.TryParse(num)
if v then yield vp|]
let symbolArray = [|for symbol in intInput do
match symbol with
| "+" -> yield symbol
| "-" -> yield symbol
| "/" -> yield symbol
| "*" -> yield symbol
| _ -> ignore 0|]
calc()
match chosenIn with
| "1" -> calc()
| "2" -> printfn "File"
| _ -> printfn "Invalid"
0 // return an integer exit code
问题不明确,少数代码片段对澄清问题的可能性很少有帮助。当前代码接受“1 2 3 4”作为输入,就像接受“+ - /”或“1 2/+ 3 * *”一样。请澄清这些情况下的预期行为。 –
其中一个主要问题是对于''',''和'*'签名是'int - > int - > int',但对于'/'它可以是'int - > int - > int ''或'int - > int - > float'这就是为什么如果你看看某些例子,你会看到'/'的答案。此外,输入应与操作符和操作数结合成一个堆栈,以便可以使用[反向波兰表示法](https://en.wikipedia.org/wiki/Reverse_Polish_notation)。 –
我希望用户输入简单的总和,如“4 + 2”,应用程序将字符串解析为输入字符串数组,然后将输入字符串数组解析为两个数组,一个用于数字,一个用于符号如 numArray = [| 4; 2; |] symArray = [| “+” |]。 然后调用以这两个数组为参数的sum函数。 该函数将查看符号数组中的第一个符号,并根据该符号确定在num数组中的前两个元素上使用哪个运算符。并用新的计算出的数字返回一个新的数组数组。 –