Emulation of lisp cons cells in Tcl

The list in lisp is a series of cons cons, but in Tcl, the list is a string with a space separating the elements. To translate code from lisp to tcl, you can simply take the lisp lists and translate them into Tcl lists. However, this leads to problems with side effects that do not fall into Tcl code. For example, consider this code in lisp:

(setq a (list 1 2 3 4))
(let ((b a)
      (a (cddr a)))
  (declare (special a b))
  (setf (cadr b) ‘b)
  (setf (cadr a) ‘d)
  (print a))
(print a)

;; Results in:
(3 d)
(1 b 3 d)

Is there a Tcl package that will provide better emulation of lisp lists in Tcl? Does such a package provide a simple conversion to regular Tcl lists?

What could be the above code in Tcl using such a package?

+5
source share
1 answer

Lisp cons Tcl - . Lisp , ; . Tcl , "1 2 3 4", , , ; Tcl ( , ...) , Tcl ; , . ( , , , , , , .)

cons . :

proc cons {a b} {
    global gensym cons
    set handle G[incr gensym]
    set cons($handle) [list $a $b]
    return $handle
}
proc car {handle} {
    global cons
    return [lindex $cons($handle) 0]
}
proc cdr {handle} {
    global cons
    return [lindex $cons($handle) 1]
}
proc setCar {handle value} {
    global cons
    lset cons($handle) 0 $value
}
# Convenience procedures
proc makeFromList args {
    set result "!nil"
    foreach value [lreverse $args] {
        set result [cons $value $result]
    }
    return $result
}
proc getAsList {handle} {
    set result {}
    while {$handle ne "!nil"} {
        lappend result [car $handle]
        set handle [cdr $handle]
    }
    return $result
}

set a [makeFromList 1 2 3 4]
# Use some local context; Tcl doesn't have anything exactly like Lisp "let"
apply {a {
    set b $a
    set a [cdr [cdr $a]]
    setCar [cdr $b] "b"
    setCar [cdr $a] "d"
    puts [getAsList $a]
}} $a
puts [getAsList $a]

(, Lisp Tcl , ).

+7

All Articles