【发布时间】:2020-03-05 15:18:14
【问题描述】:
我正在编写一个函数来处理 F# 中的后缀评估。这就是我目前所拥有的评估功能
//Postfix evaluation of string expr given variables bound to values as specified in vars
let (numSt:int list) = []
let rec innerEval (vars:(List<(string * int)>)) (stack: int list) (expr:string) =
//Head and Tail for stack, head and tail for expr
let chExpr = Seq.toList expr
match expr with
|[] -> stack.Head
|head::tail ->
if head = '+' then
let pushVal = stack.Head + stack.Tail.Head
let newStack = pushVal::stack.Tail
innerEval vars newStack tail
elif head = '-' then
let pushVal = stack.Head - stack.Tail.Head
let newStack = pushVal::stack.Tail
innerEval vars newStack tail
elif head = '/' then
let pushVal = stack.Head / stack.Tail.Head
let newStack = pushVal::stack.Tail
innerEval vars newStack tail
elif head = '*' then
let pushVal = stack.Head * stack.Tail.Head
let newStack = pushVal::stack.Tail
innerEval vars newStack tail
elif head = '$' then
let fstSt = stack.Head
let sndSt = stack.Tail.Head
let nhead = [fstSt; sndSt]
let st = nhead @ stack.Tail.Tail
innerEval vars st tail
elif head = '@' then
let nhead = tail.Head
let newVars = newVarList nhead vars stack.Head //helper function newVarList
innerEval newVars stack.Tail tail
//else it's a letter that needs to give back a number
else
let addNum = (getVal head vars) //get the number
let newStack = addNum::stack //push that onto stack
innerEval vars newStack expr //return to recursion on newStack
我知道这很罗嗦,但是当我尝试运行此代码时,我在代码中收到一个错误,显示为
pa4.fs(1194,38): error FS0001: This expression was expected to have type
'string'
but here has type
'char'
所以我的问题不一定是关于代码本身(除非有人能看出它有什么问题),而是关于错误消息:显然这意味着我有一个类型不正确的元素,但是 (1194, 38 ) 意思是?我假设是第 38 行,但每次运行代码时都会增加较大的数字,我不确定这意味着什么?
对不起,如果这是一个菜鸟问题,这个任务几乎没有方向!
【问题讨论】:
-
首先,菜鸟问题通常是最好的问题,因为我们希望让刚入门的人更容易! 1194 是控制台中的行,34 是列。这就是为什么这个数字每次都变大的原因,因为它也有你以前评估过的东西。我个人不喜欢这种默认设置,它对于只运行一小部分代码的人来说效果很好,但对于想要运行整个代码的人来说,它可能是一个痛点。
标签: f# f#-interactive