How to load-string to current namespace (not core)? - namespaces

I can load arbitrary Clojure source using:
(load-string source)
However, if namespace wasn't provided, it loads code to clojure.core namespace.
For example, following code:
(load-string "(defn add [a b] (+ a b))")
defines a function:
#'clojure.core/add
Now, is there a way to load that code to some other namespace, preferably the same one in which load-string function is called?
(Other than prepending a namespace declaration to source string before evaluation. I know that it would solve the problem - I'd like to know is there a preferred way)

when def needs to decide what namspace a new function should go in it looks at the the current value of the ns var and adds the new function to that namespace. because ns is a var you can dynamically bind it before you call load-string
user> (binding [*ns* (find-ns 'foo)] (load-string "(defn f [] 4)"))
#'foo/f
user> (foo/f)
4

Related

How does ecmascript-6 Function.prototype.bind() handle a class constructor?

I totally missed the ES6 revolution and I'm returning to JavaScript after 7 years, to find a host of very strange things happening.
One in particular is the way Function.prototype.bind() handles class constructors.
Consider this:
// an ES6 class
class class1 {
constructor (p) {
this.property = p;
}
}
var class2 = class1.bind(passer_by);
var class3 = class2.bind(passer_by,3);
class2() // exception, calling a constructor like a function
class3() // idem
console.log (new class1(1)) // class1 {property: 1}
console.log (new class2(2)) // class1 {property: 2}
console.log (new class3() ) // class1 {property: 3}
// An ES5-style pseudo-class
function pseudoclass1 (p) {
this.property = p;
}
var property = 0;
var passer_by = { huh:"???" }
var pseudoclass2 = pseudoclass1.bind(passer_by);
var pseudoclass3 = pseudoclass1.bind(passer_by,3);
pseudoclass1(1); console.log (property) // 1 (this references window)
pseudoclass2(2); console.log (passer_by) // Object { huh: "???", property: 2 }
pseudoclass3() ; console.log (passer_by) // Object { huh: "???", property: 3 }
console.log (new pseudoclass1(1)) // pseudoclass1 {property: 1}
console.log (new pseudoclass2(2)) // pseudoclass1 {property: 2}
console.log (new pseudoclass3() ) // pseudoclass1 {property: 3}
Apparently class2 and class3 are identified as constructors, and class3 is a partial application of class1 that can generate instances with a fixed value of the first parameter.
On the other hand, though they can still act as (poor man's) constructors, the ES5-style functions are indeed served the value of this set by bind(), as can be seen when they act on the hapless passer_by instead of clobbering global variables as does the unbound pseudoclass1.
Obviously, all these constructors somehow access a value of this that allows them to construct an object. And yet their this are supposedly bound to another object.
So I guess there must be some mechanism at work to feed the proper this to a constructor instead of whatever parameter was passed to bind().
Now my problem is, I can find bits of lore about it here and there, even some code apparently from some version of Chrome's V8 (where the function bind() itself seems to do something special about constructors), or a discussion about a cryptic FNop function inserted in the prototype chain, and, if I may add, the occasional piece of cargo cult bu[beep]it.
But what I can't find is an explanation about what is actually going on here, a rationale as to why such a mechanism has been implemented (I mean, with the new spread operator and destructuring and whatnot, wouldn't it be possible to produce the same result (applying some arguments to a constructor) without having to put a moderately documented hack into bind()?), and its scope (it works for constructors, but are there other sorts of functions that are being fed something else than the value passed to bind() ?)
I tried to read both the 2015 and 2022 ECMA 262 specifications, but had to stop when my brains started leaking out of my ears. I traced back the call stack as:
19.2.3.2
9.4.1.3
9.4.1.2
7.3.13
where something is said about constructors, in a way: "If newTarget is not passed, this operation is equivalent to: new F(...argumentsList)". Aha. So this pseudo-recursive call should allow to emulate a new somehow... Erf...
I'd be grateful if some kind and savvy soul could give me a better idea of what is going on, show me which part(s) of the ECMA specs deal with this mechanism, or more generally point me in the right direction.
I'm tired of banging my head against a wall, truth be told. This bit of Chrome code that seems to indicate bind() is doing something special for constructors is just incomprehensible for me. So I would at least like an explanation about it, if everything else fails.
This doesn't have anything to do with classes specifically but with how .bind works.
You have been on the right track. The most relevan section here is 9.4.1.2.
Just as a recap: ECMAScript distinguishes between two types of functions: callable functions and constructable functions. Function expressions/declarations are both, whereas e.g. class constructors are only constructable and arrow functions are only callable.
In the specification this is represented by function's internal [[Call]] and [[Construct]] methods.
new will trigger the invocation of the internal [[Construct]] method.
.bind will return a new function object with different implementations for [[Call]] and [[Construct]]. So what does the "bound" version of [[Construct]] look like?
9.4.1.2 [[Construct]] ( argumentsList, newTarget )
When the [[Construct]] internal method of a bound function exotic object, F that was created using the bind function is called with a list of arguments argumentsList and newTarget, the following steps are taken:
Let target be F.[[BoundTargetFunction]].
Assert: IsConstructor(target) is true.
Let boundArgs be F.[[BoundArguments]].
Let args be a new list containing the same values as the list boundArgs in the same order followed by the same values as the list argumentsList in the same order.
If SameValue(F, newTarget) is true, set newTarget to target.
Return ? Construct(target, args, newTarget).
What this means is that the bound constructor will "construct" the original function (F.[[BoundTargetFunction]]) with the bound arguments (F.[[BoundArguments]]) and the passed in arguments (argumentsList), but it completely ignores the bound this value (which would be F.[[BoundThis]]).
but are there other sorts of functions that are being fed something else than the value passed to bind() ?
Yes, arrow functions. Arrow functions do not have their own this binding (the value from the closest this providing environment is used instead), so bound arrow functions also ignore the bound this value.

Gradle add function to subproject (best practice)

This is a question that has multiple parts.
Gradle seems to have 2 ways to define a function
Type one:
def func1 = { param -> ...}
Type 2
def func2 (OptionalType param){...}
I prefer to use Type 2 not only because I don't know how to define the type for a parameter for func1 (question part 1 is how to set the type for a func type 1 param), but also because it reads better.
But I found that I can do
subprojects { ext.func1 = func1 }
But
subprojects { ext.func2 = func2 }
doesn't seem to work, since I'd prefer to use function type 2 I'd like to know how to serve it to subprojects, I believe this must be possible but I can't find the right syntax. (question part 2)
I hope you guys can help me.
Your func1 is not a function, but you define a closure that you assign to a variable. In Groovy (which Gradle is based upon) you can call variable that has a closure assigned like it would be a function, but essentially it is not.
So either use type one (you can also there use the optional type in the same place def func1 = { OptionalType param -> ...} but you don't need to as Groovy is dynamically typed.
Or define your function with type 2 and then make a type 1 variable that calls the type 2 function.

debugging functions in the clojurescript repl

Does anybody know a good way to debug functions in the clojureScript REPL?
The default, behavior is that the generated JS code of the function is printed.
midi.lib=> (defn f [] (println "hello"))
#'midi.lib/f
midi.lib=> f
#object[midi$lib$f "function midi$lib$f(){
return cljs.core.println.call(null,"hello");
}"]
With longer functions this gets annoying. For many debugging cases, simply the name of the function would be sufficient..
There is currently no support for controlling how function values print in ClojureScript.
But, if you are OK with extending the JavaScript function type, you can evaluate the following in a REPL
(extend-type js/Function
IPrintWithWriter
(-pr-writer [obj writer _]
(let [name (.-name obj)
name (if (empty? name)
"Function"
name)]
(write-all writer "#object[" name "]"))))
and then your example function value would print as #object[midi$lib$f].
Try using the Figwheel REPL, it doesn't print out the generated JS, and behaves similarly to a Clojure REPL.

Calling function from another module in Verilog

I am trying to instantiate and use a function that has been defined in another module.
module simple_function();
function myfunction;
input a, b, c, d;
begin
myfunction = ((a+b) + (c-d));
end
endfunction
endmodule
module function_calling(a, b, c, d, e, f);
input a, b, c, d, e ;
output f;
wire f;
`include "myfunction.v"
assign f = (myfunction (a,b,c,d)) ? e :0;
endmodule
I got this code from http://www.asic-world.com/verilog/task_func1.html
However, when I execute the same in ModelSim Altera Starter Edition 10.0d, I get this error:
Cannot open `include file "myfunction.v".
Where am I going wrong?
An include directive has the same effect as copying and pasting that code in the same spot. From your code it looks like you are trying to define a module (simple_function) inside of another module (function_calling), which is not allowed.
Your function does not need to be contained inside a module. You should change myfunction.v to just contain the myfunction definition and remove the simple_function module entirely. That way when myfunction.v is included it has the same effect as the function being declared in function_calling.
Another way for calling a function of one module into another module is through interface. You can pass interface ports into first module due to which interface will get the all functions and tasks into it, and then interface can be pass into second module, in this way second module can get tasks and functions of first module.

TclOO class inside namespace: calling namespace procs give errors

I'm experimenting a little with TclOO from Tcl8.6 and Rivet, but I'm in trouble, because I'm not able to do what I want.
The problem is simply reproduceable with the following code inside a .rvt file:
<?
proc dumbproc {} {
puts "this is dumbproc ([namespace current])"
}
oo::class create foo {
method bar {} {
puts "this is bar ([namespace current])"
dumbproc
}
}
set obj [foo new]
dumbproc
$obj bar
If I simply look at the code, it seems it should work as expected, but it really doesn't because a subtle behavior of the Rivet package and the specific configuration choosen.
In this example, I'm using a .rvt file whose code is executed inside the ::request namespace, so the fully qualified name of the dumbproc procedure is ::request::dumbproc. When the name resolution algorithm is called inside the bar method, it searches for dumbproc inside ::oo::Obj12, then in ::oo, and finally in ::, without finding it and giving the following error.
this is dumbproc (::request) this is bar (::oo::Obj16)
invalid command name "dumbproc"
while executing
"dumbproc"
(class "::request::foo" method "bar" line 3)
invoked from within
"$obj bar"
(in namespace eval "::request" script line 21)
invoked from within
"namespace eval request {
puts -nonewline ""
proc dumbproc {} {
puts "this is dumbproc ([namespace current])"
}
oo::class create..."
So, Tcl is right in doing what it does, a feature, then. But the behavior is unpredictable because when you write some class code, you must know the context it will be used in.
Indeed, I get the same error if I drop the starting <? Rivet magic, put the code inside a test.tcl file and use it in an interactive session:
$ tclsh
% namespace eval ::myns {source test.tcl}
this is dumbproc (::myns)
this is bar (::oo::Obj12)
invalid command name "dumbproc"
I tried to solve the issue by prepending the current namespace to the class creation code
::oo::class create [namespace current]::foo { ... }
then, I also tried to create the obj object inside the namespace
::oo::class create [namespace current]::foo { ... }
namespace eval [namespace current] {set obj [[namespace current]::foo new]}
then, I switched to the create method of the class for giving the object a qualified name which includes the namespace
foo create [namespace current]::obj
obj bar
but everything was unsuccessful. Every trial shows that, no matter how I do it, a method inside a TclOO class is always executed inside its object unique namespace. Am I wrong?
Is there a way to get what I want? Is TclOO not intended to work that way, and in this case why? What really surprise me is this context-dependend behavior, which I'm not sure it's the right thing, but maybe I'm completely wrong and there are sound cases for it, which I'm missing.
The interior of each TclOO object is in reality its own namespace. You can use self namespace or namespace current inside your methods to get the name of the namespace, or info object namespace $theobj to get the namespace from anywhere. The only command placed by default in the namespace is my (for calling private methods), and some commands in other namespaces are made available through the standard Tcl namespace path mechanism (this is how you get self and next available).
The simplest way to fix this would probably be to add this to the foo class's constructor:
namespace path [list {*}[namespace path] ::request]
In your specific case, you'd have to actually add a constructor...
constructor {} {
namespace path [list {*}[namespace path] ::request]
# If you had a non-trivial constructor in a superclass, you'd need to call
# [next] too.
}
Longer term, it may be reasonable to ask for a mechanism for adding to the list of namespaces that are used to make the default for objects of a class. If you want that, do submit a feature request…
[EDIT]: If you're just after adding the parent namespace to the current object's command resolution path, you can do that by adding a bit more magic:
oo::class create foo {
self {
method create args {
set ns [uplevel 1 {namespace current}]
next {*}[linsert $args 1 $ns]
}
method new args {
set ns [uplevel 1 {namespace current}]
next {*}[linsert $args 0 $ns]
}
}
constructor {creatorNS args} {
namespace path [list {*}[namespace path] $creatorNS]
}
method bar {} {
puts "this is bar ([namespace current])"
dumbproc
}
}
That will then automatically put the current namespace at creation on the path of the instance. If you're doing this in many classes, you probably want to create a metaclass with the majority of machinery in it, but the above technique (a self declaration of some methods on the foo class object itself) works fine for simple cases.