What is the ClojureScript equivalent of a JavaScript scope taking an argument - closures

I want to write a program which adds complex behavior to a div (think some kind of interactive graphic, for example). I would like to be able to pass a div to a function in the library and have the library add behavior to the div.
If I were doing this in JavaScript, I would write the following.
In my_page.html:
<div id="program-container"></div>
<script src="my_library.js" type="text/javascript"></script>
<script type="text/javascript">
useDivForACoolProgram(document.getElementById("program-container"));
</script>
In my_library.js:
function useDivForACoolProgram(div) {
var x = 2;
var y = 3;
function setup() {
div.innerHTML = "Getting ready to run...";
doMainSetup();
}
function doMainSetup() {
...
// Lots more functions, many of which refer to div
}
Note that the library exposes a single function which accepts a div. When we pass it a div, the library keeps all of its state in a closure associated with the passed div, which would potentially allow me to add this behavior to many divs on the page if I were so inclined.
I want to do the same sort of thing in ClojureScript. My first attempt was as follows:
(defn use-div-for-a-cool-program [div]
(def x 2)
(def y 3)
(defn setup []
(set! (.innerHTML div) "Getting ready to run...")
(do-main-setup))
(defn do-main-setup []
...
;; Lots more functions, many of which refer to div
)
But this doesn't work, because def and defn define variables at the module's scope rather than defining variables local to use-div-for-a-cool-program. If I were to call use-div-for-a-cool-program multiple times with different divs, all of the new defs and defns would override the old each time.
One solution would be to use let instead, but this is a bit unsatisfying because it forces us to give the implementation of functions before they can be referenced and is also hard to read, e.g.
(defn use-div-for-a-cool-program [div]
(let [x 2
y 3
do-main-setup (fn []
...)
setup (fn []
(set! (.innerHTML div) "Getting ready to run...")
(do-main-setup))
;; Lots more functions, many of which refer to div
]
(setup)))
Is there a better solution?

My solution is not what you want to hear :) You pass div as an argument to each function. Instead of coupling the functions to div implicitly you specify explicitly that a div is needed:
(defn do-main-setup [div]
...)
(defn setup [div]
(set! (.innerHTML div) "Getting ready to run...")
(defn use-div-for-a-cool-program [div]
(let [x 2
y 3]
(do-main-setup div))
;; Lots more functions, many of which refer to div explicitly
(setup div)))
Even if this is a little bit more verbose (as you pass div every time) it makes your intent clear. I use a closure when I want to return the function and call it later, remembering the scope in which it was defined. I don't see how it helps to define those functions as closures and call them precisely after.
If you want to keep some state associated to your div I would also do so explicitly. For example, if you want to keep count of how many clicks your div received I would do this:
(defn add-state-handler [div state]
(set! (.onclick div) #(swap! state inc)))
(defn use-div-for-a-cool-program [div]
(let [x 2
y 3
counter (atom 0)]
(do-main-setup div))
(add-state-handler div counter)
;; Other functions that reference div and counter
(setup div)))
In short, I would avoid handling any state or mutable values (counter or div) implicitly. If you have to render a view that depends on some changing state I would recommend any Clojurescript React wrapper like Om or Reagent.

Related

How to write a recursive anonymous function in Dart

Lets say I wanted to write a recursive anonymous function to calculate factorial values.
print(((int a) => a == 1? 1 : a * this(a - 1))(4));
I would expect this to print 24, which is 4! (this function is obviously prone to issues with negative numbers, but that's beside the point)
The problem is that this doesn't refer to the anonymous function in order to make a recursive call.
Is this something that's possible in dart? I've seen it in python before, where a function is assigned to a variable with the walrus operator ( := ) and is also recursive.
Here is an example that creates a list of the average value on each level of a binary tree:
return (get_levels := lambda l: ([mean(node.val for node in l)] + get_levels([child for node in l for child in [node.left, node.right] if child])) if l else [])([root])
As you can see, the lambda is called get_levels. It calculates the average of the current level, then makes a recursive call on the next level of the binary tree and appends it to the list of previous level averages.
The closest that I could come up with is this:
var getLevels;
List<double> averageOfLevels(TreeNode? root) {
return root == null ? [] : (getLevels = (List<TreeNode> level) => level.isNotEmpty ? <double>[level.map((node) => node.val).fold(0, (int l, int r) => l+r) / level.length] + getLevels([for(var node in level) ...[node.left, node.right]].whereType<TreeNode>().toList()) : <double>[])([root]);
}
But, as you can see, this required an additional line where the variable is defined ahead of time.
Is it possible to achieve something more similar to the python example using callable classes?
There's a classic Lisp/Scheme problem of how to create a recursive lambda. The same technique of creating one anonymous function that takes itself as an argument and then using another anonymous function to pass the first anonymous function to itself can be applied to Dart (albeit by sacrificing some type-safety; I can't think of a way to strongly type a Function that takes its own type as an argument). For example, a recursive factorial implementation:
void main() {
var factorial = (Function f, int x) {
return f(f, x);
}((Function self, int x) {
return (x <= 1) ? 1 : x * self(self, x - 1);
}, 4);
print('4! = $factorial'); // Prints: 4! = 24
}
All that said, this seems like a pretty contrived, academic problem. In practice, just create a named function. It can be a local function if you want to avoid polluting a global namespace. It would be far more readable and maintainable.
Is it possible to achieve something more similar to the python example using callable classes?
I'm not sure where you're going with that since Dart neither allows defining anonymous classes nor local classes, so even if you made a callable class, it would violate your request for being anonymous.

Maxima: Is there any way to make functions defined within the main function be local, in a similar way to local variables?

I wonder if there is any way to make functions defined within the main function be local, in a similar way to local variables. For example, in this function that calculates the gradient of a scalar function,
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
The variable gradient that has been defined inside the main function grad(var,f) has no effect outside the main function, as it is inside the aux list. However, I have observed that the function DfDx, despite being inside the aux list, does have an effect outside the main function.
Is there any way to make the sub-functions defined inside the main function to be local only, in a similar way to what can be made with local variables? (I know that one can kill them once they have been used, but perhaps there is a more elegant way)
To address the problem you are needing to solve here, another way to compute the gradient is to say
grad(var, e) := makelist(diff(e, var1), var1, var);
and then you can say for example
grad([x, y, z], sin(x)*y/z);
to get
cos(x) y sin(x) sin(x) y
[--------, ------, - --------]
z z 2
z
(There isn't a built-in gradient function; this is an oversight.)
About local functions, bear in mind that all function definitions are global. However you can approximate a local function definition via local, which saves and restores all properties of a symbol. Since the function definition is a property, local has the effect of temporarily wiping out an existing function definition and later restoring it. In between you can create a temporary function definition. E.g.
foo(x) := 2*x;
bar(y) := block(local(foo), foo(x) := x - 1, foo(y));
bar(100); /* output is 99 */
foo(100); /* output is 200 */
However, I don't this you need to use local -- just makelist plus diff is enough to compute the gradient.
There is more to say about Maxima's scope rules, named and unnamed functions, etc. I'll try to come back to this question tomorrow.
To compute the gradient, my advice is to call makelist and diff as shown in my first answer. Let me take this opportunity to address some related topics.
I'll paste the definition of grad shown in the problem statement and use that to make some comments.
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
(1) Maxima works mostly with expressions as opposed to functions. That's not causing a problem here, I just want to make it clear. E.g. in general one has to say diff(f(x), x) when f is a function, instead of diff(f, x), likewise integrate(f(x), ...) instead of integrate(f, ...).
(2) When gradient and Dfdx are to be the local variables, you have to name them in the list of variables for block. E.g. block([gradient, Dfdx], ...) -- Maxima won't understand block([aux], aux: ...).
(3) Note that a function defined with square brackets instead of parentheses, e.g. f[x] := ... instead of f(x) := ..., is a so-called array function in Maxima. An array function is a memoizing function, i.e. if f[x] is called two or more times, the return value is only computed once, and then returned every time thereafter. Sometimes that's a useful optimization when the domain of the function comprises a finite set.
(4) Bear in mind that x_1, x_2, x_3, are distinct symbols, not related to each other, and not related to x[1], x[2], x[3], even if they are displayed the same. My advice is to work with subscripted symbols x[i] when i is a variable.
(5) About building up return values, try to arrange to compute the whole thing at one go, instead of growing the result incrementally. In this case, makelist is preferable to for plus append.
(6) The return function in Maxima acts differently than in other programming languages; it's a little hard to explain. A function returns the value of the last expression which was evaluated, so if gradient is that last expression, you can just write grad(var, f) := block(..., gradient).
Hope this helps, I know it's obscure and complex. The Maxima programming language was not designed before being implemented, and some of the decisions are clearly questionable at the long interval of more than 50 years (!) later. That's okay, they were figuring it out as they went along. There was not a body of established results which could provide a point of reference; the original authors were contributing to what's considered common knowledge today.

Passing inline function to inline function in F#

Is there any way to trick the compiler to take inline function A as a parameter of inline function B and create one big inline function with no calls?
Let's assume we have piece of code defines as below:
let inline action i = printfn "%d" i // printfn is for demo, originally some math
let inline iter lo hi func = for i = lo to hi do func i
iter 0 10 action
Usually, inline functions cannot be passed as function (they can, but they are not inline anymore, as they cannot be inlined into existing, already compiled function, so they get passed as "regular" collapsed function).
In this this case though, both function are inline so when iter gets expanded it is technically possible to inline action into it. It does not happen (generated IL definitely CALLS action) and JIT compiler doesn't seem to inline action either.
I wouldn't care but this iter contains some additional logic which needs to be hidden, but action is very short and whole thing is time critical.
Anyway, imperative code which I would expect the inline version to be expanded to is 100% faster (takes 50% of the time).
for i = lo to hi do action i
Suggestions? F# 4.0 maybe? Some magic keywords?

maps,filter,folds and more? Do we really need these in Erlang?

Maps, filters, folds and more : http://learnyousomeerlang.com/higher-order-functions#maps-filters-folds
The more I read ,the more i get confused.
Can any body help simplify these concepts?
I am not able to understand the significance of these concepts.In what use cases will these be needed?
I think it is majorly because of the syntax,diff to find the flow.
The concepts of mapping, filtering and folding prevalent in functional programming actually are simplifications - or stereotypes - of different operations you perform on collections of data. In imperative languages you usually do these operations with loops.
Let's take map for an example. These three loops all take a sequence of elements and return a sequence of squares of the elements:
// C - a lot of bookkeeping
int data[] = {1,2,3,4,5};
int squares_1_to_5[sizeof(data) / sizeof(data[0])];
for (int i = 0; i < sizeof(data) / sizeof(data[0]); ++i)
squares_1_to_5[i] = data[i] * data[i];
// C++11 - less bookkeeping, still not obvious
std::vec<int> data{1,2,3,4,5};
std::vec<int> squares_1_to_5;
for (auto i = begin(data); i < end(data); i++)
squares_1_to_5.push_back((*i) * (*i));
// Python - quite readable, though still not obvious
data = [1,2,3,4,5]
squares_1_to_5 = []
for x in data:
squares_1_to_5.append(x * x)
The property of a map is that it takes a collection of elements and returns the same number of somehow modified elements. No more, no less. Is it obvious at first sight in the above snippets? No, at least not until we read loop bodies. What if there were some ifs inside the loops? Let's take the last example and modify it a bit:
data = [1,2,3,4,5]
squares_1_to_5 = []
for x in data:
if x % 2 == 0:
squares_1_to_5.append(x * x)
This is no longer a map, though it's not obvious before reading the body of the loop. It's not clearly visible that the resulting collection might have less elements (maybe none?) than the input collection.
We filtered the input collection, performing the action only on some elements from the input. This loop is actually a map combined with a filter.
Tackling this in C would be even more noisy due to allocation details (how much space to allocate for the output array?) - the core idea of the operation on data would be drowned in all the bookkeeping.
A fold is the most generic one, where the result doesn't have to contain any of the input elements, but somehow depends on (possibly only some of) them.
Let's rewrite the first Python loop in Erlang:
lists:map(fun (E) -> E * E end, [1,2,3,4,5]).
It's explicit. We see a map, so we know that this call will return a list as long as the input.
And the second one:
lists:map(fun (E) -> E * E end,
lists:filter(fun (E) when E rem 2 == 0 -> true;
(_) -> false end,
[1,2,3,4,5])).
Again, filter will return a list at most as long as the input, map will modify each element in some way.
The latter of the Erlang examples also shows another useful property - the ability to compose maps, filters and folds to express more complicated data transformations. It's not possible with imperative loops.
They are used in almost every application, because they abstract different kinds of iteration over lists.
map is used to transform one list into another. Lets say, you have list of key value tuples and you want just the keys. You could write:
keys([]) -> [];
keys([{Key, _Value} | T]) ->
[Key | keys(T)].
Then you want to have values:
values([]) -> [];
values([{_Key, Value} | T}]) ->
[Value | values(T)].
Or list of only third element of tuple:
third([]) -> [];
third([{_First, _Second, Third} | T]) ->
[Third | third(T)].
Can you see the pattern? The only difference is what you take from the element, so instead of repeating the code, you can simply write what you do for one element and use map.
Third = fun({_First, _Second, Third}) -> Third end,
map(Third, List).
This is much shorter and the shorter your code is, the less bugs it has. Simple as that.
You don't have to think about corner cases (what if the list is empty?) and for experienced developer it is much easier to read.
filter searches lists. You give it function, that takes element, if it returns true, the element will be on the returned list, if it returns false, the element will not be there. For example filter logged in users from list.
foldl and foldr are used, when you have to do additional bookkeeping while iterating over the list - for example summing all the elements or counting something.
The best explanations, I've found about those functions are in books about Lisp: "Structure and Interpretation of Computer Programs" and "On Lisp" Chapter 4..

Dynamic binding of functions in Clojure

I have an algorithm which uses a bunch of different functions or steps during it's work. I would like to run the algorithm with different possible functions bound to those steps. In essence I want to prepare some sets of values (which specific function should be bound to this specific step) and run my algorithm with every one of those sets. And to capture results of every run alongside with input set.
Something like that:
(binding [step1 f1
step2 f2]
(do-my-job))
(binding [step1 f11
step2 f22]
(do-my-job))
but with dynamic binding expressions.
What are my options?
So you are trying to do something like a parameter sweep?
I can't see why you need to do a dynamic binding. Your algorithm is defined in terms of first class function calls. Just pass the functions in as parameters to your algorithms.
To try all the values, just generate a permutation of the values, and run map over this list. You will get all the results from this.
because binding is a macro you will need to write a macro that generates the dynamic binding forms.
Well, it seems I have it working the following way:
(def conditions [[`step1 f1 `step2 f2] [`step1 f11 `step2 f22]])
(map #(eval `(binding ~% body)) conditions)
So, I have tested this and as far as I can see, it all just works.
In the example below, I create a var, then rebind this var to a function.
As you can see the call to the function happens outside of the lexical scope of
binding form, so we have dynamic binding here.
(def
^{:dynamic true}
*bnd-fn*
nil
)
(defn fn1 []
(println "fn1"))
(defn fn2 []
(println "fn2"))
(defn callfn []
(*bnd-fn*))
;; crash with NPE
(callfn)
;; prints fn1
(binding [*bnd-fn* fn1]
(callfn))
;; prints fn2
(binding [*bnd-fn* fn2]
(callfn))
I've been using a similar approach for a library of my own (Clojure-owl if you are interested!), although in my case the thing I with to dynamically rebind is a Java object.
In that case, while I have allowed dynamic rebinding, in most cases I don't; I just use a different java object for different name spaces. This works nicely for me.
In reply to your comment, if you want to have a single binding form, then, this is easy to achieve. Add the following code.
(defn dobinding [fn]
(binding [*bnd-fn* fn]
(callfn)))
(dorun
(map dobinding
[fn1 fn2]))
The function dobinding runs all of the others. Then I eval this with a single map (and dorun or you get a lazy sequence). This runs two functions for each step. Obviously, you will need to pass a list of lists in. You should be able to parallelize the whole lot if you choose.
This is a lot easier than trying to splice in the whole vector. The value in a binding form is evaluated so it can be anything you like.

Resources