Truly declarative language?

后端 未结 19 2177
梦毁少年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
    
    0 讨论(0)
  • 2021-02-04 02:15

    not sure how well metapost (1) would work for your application, but it is declarative.

    0 讨论(0)
  • 2021-02-04 02:18

    Wanting to have two definitions of X is inherently imperative. In a truly declarative language you have a single definition of a variable in a single scope. The behavior you want from Excel corresponds to editing the program.

    0 讨论(0)
  • 2021-02-04 02:19

    JavaFX will do that for you if you use bind instead of = for Z

    0 讨论(0)
  • 2021-02-04 02:21

    Groovy and the magic of closures.

    def (x, y) = [ 10, 20 ]
    
    def z = { x + y }
    
    assert 30 == z()
    
    x = 50
    
    assert 70 == z()
    
    def f = { n -> n + 1 }  // define another closure
    
    def g = { x + f(x) }    // ref that closure in another
    
    assert 101 == g()       // x=50, x + (x + 1)
    
    f = { n -> n + 5 }     // redefine f()
    
    assert 105 == g()      // x=50, x + (x + 5)
    

    It's possible to add automagic memoization to functions too but it's a lot more complex than just one or two lines. http://blog.dinkla.net/?p=10

    0 讨论(0)
  • 2021-02-04 02:22

    Two things you can look at are the cells lisp library, and the Modelica dynamic modelling language, both of which have relation/equation capabilities.

    0 讨论(0)
提交回复
热议问题