我正在编写一个编程语言解释器。
我需要正确的代码习惯来评估一系列表达式以获取它们的一系列值,并在评估发生时将状态从一个评估器传播到下一个评估器。我想要一个函数式编程习语。
这不是折叠,因为结果像地图一样出来。这不是地图,因为横穿了国家道具。
我所拥有的是我用来试图解决这个问题的代码。先忍受几行测试台:
// test rig
class MonadLearning extends JUnit3Suite {
val d = List("1", "2", "3") // some expressions to evaluate.
type ResType = Int
case class State(i : ResType) // trivial state for experiment purposes
val initialState = State(0)
// my stub/dummy "eval" function...obviously the real one will be...real.
def computeResultAndNewState(s : String, st : State) : (ResType, State) = {
val State(i) = st
val res = s.toInt + i
val newStateInt = i + 1
(res, State(newStateInt))
}
我目前的解决方案。使用在评估地图主体时更新的 var:
def testTheVarWay() {
var state = initialState
val r = d.map {
s =>
{
val (result, newState) = computeResultAndNewState(s, state)
state = newState
result
}
}
println(r)
println(state)
}
我使用 foldLeft 有我认为不可接受的解决方案,它执行我所说的“折叠时将其包起来”的成语:
def testTheFoldWay() {
// This startFold thing, requires explicit type. That alone makes it muddy.
val startFold : (List[ResType], State) = (Nil, initialState)
val (r, state) = d.foldLeft(startFold) {
case ((tail, st), s) => {
val (r, ns) = computeResultAndNewState(s, st)
(tail :+ r, ns) // we want a constant-time append here, not O(N). Or could Cons on front and reverse later
}
}
println(r)
println(state)
}
我还有几个递归变体(很明显,但也不清楚或动机不强),其中一个使用几乎可以容忍的流:
def testTheStreamsWay() {
lazy val states = initialState #:: resultStates // there are states
lazy val args = d.toStream // there are arguments
lazy val argPairs = args zip states // put them together
lazy val resPairs : Stream[(ResType, State)] = argPairs.map{ case (d1, s1) => computeResultAndNewState(d1, s1) } // map across them
lazy val (results , resultStates) = myUnzip(resPairs)// Note .unzip causes infinite loop. Had to write my own.
lazy val r = results.toList
lazy val finalState = resultStates.last
println(r)
println(finalState)
}
但是,我想不出像上面的原始“var”解决方案那样紧凑或清晰的东西,我愿意接受,但我认为吃/喝/睡觉单子成语的人只会说.. . 使用这个... (希望如此!)