【发布时间】:2016-11-03 22:59:56
【问题描述】:
我必须在 F# 中创建一个计算器,并且我被困在一个任务上。
我需要将总和作为字符串传递到控制台,例如"4 + 5" 并解析计算。
有什么想法吗?
任何帮助将不胜感激
open System
let rec calculator() =
printf "Choose a sum type \n1: Addition\n2: Subtraction\n3: Mulitiplication\n4: Division\n\n\n"
let input = Console.ReadLine();
printf "now type in 2 numbers\n"
let num1 = Console.ReadLine();
let num2 = Console.ReadLine();
let a : int = int32 num1
let b : int = int32 num2
let addition x y = x + y
let subtraction x y = x - y
let multiply x y = x * y
let divide x y = x / y
match input with
| "1" -> printfn("The result is: %d")(addition a b)
| "2" -> printfn("The result is: %d")(subtraction a b)
| "3" -> printfn("The result is: %d")(multiply a b)
| "4" -> printfn("The result is: %d")(divide a b)
ignore(Console.ReadKey())
ignore(calculator())
calculator()
【问题讨论】:
-
感兴趣的:Formula Calculator
-
公式计算器示例的详细信息超出了您的需要。我发布它是因为大多数提出类似问题的人都需要随着他们的进步而添加更多细节。如果你花时间去理解它,那么你就会得到答案,并且更好地理解解析和评估表达式。
-
FParsec 有一个相当简洁的例子:bitbucket.org/fparsec/main/src/…
标签: string parsing f# calculator f#-interactive