Truly declarative language?

后端 未结 19 2615
梦毁少年i
梦毁少年i 2021-02-04 01:26

Does anyone know of a truly declarative language? The behavior I\'m looking for is kind of what Excel does, where I can define variables and formulas, and have the formula\'s re

19条回答
  •  天命终不由人
    2021-02-04 02:15

    You can do this in Tcl, somewhat. In tcl you can set a trace on a variable such that whenever it is accessed a procedure can be invoked. That procedure can recalculate the value on the fly.

    Following is a working example that does more or less what you ask:

    proc main {} {
        set x 10
        set y 20
        define z {$x + $y}
    
        puts "z (x=$x): $z"
        set x 50
        puts "z (x=$x): $z"
    }
    
    
    proc define {name formula} {
        global cache
        set cache($name) $formula
        uplevel trace add variable $name read compute
    }
    
    proc compute {name _ op} {
        global cache
        upvar $name var
        if {[info exists cache($name)]} {
            set expr $cache($name)
        } else {
            set expr $var
        }
        set var [uplevel expr $expr]
    }
    
    main
    

提交回复
热议问题