[英]Simple calculator in F# using regular expressions
我的老師要求我創建一個簡單的計算器(支持 +、-、* 和 / 的計算器)。 它應該接受用戶輸入並打印結果。 它應該永遠運行並保存最后的計算結果。
我想通過使用正則表達式來做到這一點,因為我最近被介紹過這個,但我不知道如何讓它工作。 這是我創建的,但它不起作用。
let getInput () =
System.Console.Write ("give input: ")
let s = System.Console.ReadLine ()
s
let simpleCalc () =
let numb1 = "[0-9]*"
let numb2 = "[0-9]*"
let operator = "[+-*/]"
while true do
let s = getInput ()
match s with
| "([0-9]*)([+-*/]?)([0-9]*)" [ int1; operator; int2 ] -> int1 operator int2
| _ -> printfn "thas no simple maf"
正如評論中提到的,您需要在某處使用正則表達式。 執行此操作的一種方法與您所寫的非常接近,是定義一個活動模式,如果輸入與給定的正則表達式匹配並以列表形式返回匹配的組,則該模式會成功:
open System.Text.RegularExpressions
let (|Regex|_|) regex input =
let res = Regex.Match(input, regex)
if res.Success then Some (List.tail [for g in res.Groups -> g.Value])
else None
然后可以將基本算術的簡單評估器實現為:
let s = "123*5"
let ops = dict [ "+", (+); "-", (-); "*", (*); "/", (/)]
match s with
| Regex "([0-9]*)([\+\-\*\/])([0-9]*)" [left; op; right] ->
ops.[op] (int left) (int right)
| _ -> -1
請注意,我們需要將運算符的字符串表示形式轉換為我們可以以某種方式調用的 F# 函數 - 所以我使用dict
定義了一個簡單的查找表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.