Topic variable: Difference between revisions

Go solution
m (→‎{{header|Sidef}}: improved the comment)
(Go solution)
Line 53:
 
The word '''>R''' places the item on the return stack and the word '''R>''' retrieves it from the return stack - an experienced Forth programmer would optimize this definition even further. Note that for technical reasons all words listed cannot be used outside definitions, so it may be argued that Forth doesn't have topic variables.
 
=={{header|Go}}==
Go has nothing like this in the bare language, but the template package of the standard library has a similar mechanism. Templates can have named variables, but they also have a cursor, represented by a period '.' and called "dot", that refers to a current value.
<lang go>package main
 
import (
"math"
"os"
"strconv"
"text/template"
)
 
func sqr(x string) string {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return "NA"
}
return strconv.FormatFloat(f*f, 'f', -1, 64)
}
 
func sqrt(x string) string {
f, err := strconv.ParseFloat(x, 64)
if err != nil {
return "NA"
}
return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)
}
 
func main() {
f := template.FuncMap{"sqr": sqr, "sqrt": sqrt}
t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}}
square: {{sqr .}}
square root: {{sqrt .}}
`))
t.Execute(os.Stdout, "3")
}</lang>
{{out}}
<pre>
. = 3
square: 9
square root: 1.7320508075688772
</pre>
 
=={{header|J}}==
1,707

edits