我試圖在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數組中的前兩個元素上使用哪個運算符。並用新的計算出的數字返回一個新的數組數組。 –