Functions/closures
muSE doesn't use the Scheme standard lambda keyword to create functions. This language deecision is because muSE is used by non-programmers who are slightly familiar with JavaScript, but will freak out if they see things like lambda occuring anywhere. It has fn and fn: instead. fn behaves like you'd expect lambda to - capturing the lexical context in a closure. fn: creates a function which has a dynamically scoped body. Here's an example that tells you the difference between the two -
(define y 2.0)
(define f (fn (x) (+ x y)))
(define g (fn: (x) (+ x y)))
Now,
> (f 5.0)
7.0
> (g 5.0)
7.0
Fair enough, but now lets change the definition of y ..... locally!
(let ((y 4.0))
(print (f 5.0))
(print (g 5.0)))
Now f continues to use the old value of y whereas g uses the new value of y instead. The above expression will print -
7.0
9.0
No comments:
Post a Comment