CoffeeScript: calculate parse tree (like coffee -n) in a program - coffeescript

Is there a way to compute the CoffeeScript parse tree of a program (provided as a string) inside CoffeeScript without calling an external program?
For example, let's say I have a string 'square=(n)->n*n' inside a CoffeeScript program. I want to get the same output as storing this string in a file square.coffee and calling on the command line coffee -n square.coffee --- but without creating another process:
Block
Assign
Value "square"
Code
Param "n"
Block
Op *
Value "n"
Value "n"
Please, provide with your solution a link to documentation how to interpret the resulting data structure.

Just look in the source: the -n flag invokes (require 'coffee-script).nodes. The result is a syntax tree which corresponds to grammar.coffee and would be interpreted with nodes.coffee.
So this:
(require 'coffee-script').nodes 'square = (n)->n*n'
Will give you a syntax tree. Before you print it, you could use its toString method to get the same output as the coffee CLI.
For the filesystem operations, just use node's readFile or readFileSync from the fs library:
{readFileSync} = require 'fs'
{nodes} = require 'coffee-script'
nodes readFileSync('squares.coffee').toString()

Related

Perl interface with Aspell

I am trying to identify misspelled words with Aspell via Perl. I am working on a Linux server without administrator privileges which means I have access to Perl and Aspell but not, for example, Text::Aspell which is a Perl interface for Aspell.
I want to do the very simple task of passing a list of words to Aspell and having it return the words that are misspelled. If the words I want to check are "dad word lkjlkjlkj" I can do this through the command line with the following commands:
aspell list
dad word lkjlkjlkj
Aspell requires CTRL + D at the end to submit the word list. It would then return "lkjlkjlkj", as this isn't in the dictionary.
In order to do the exact same thing, but submitted via Perl (because I need to do this for thousands of documents) I have tried:
my $list = q(dad word lkjlkjlkj):
my #arguments = ("aspell list", $list, "^D");
my $aspell_out=`#arguments`;
print "Aspell output = $aspell_out\n";
The expected output is "Aspell output = lkjlkjlkj" because this is the output that Aspell gives when you submit these commands via the command line. However, the actual output is just "Aspell output = ". That is, Perl does not capture any output from Aspell. No errors are thrown.
I am not an expert programmer, but I thought this would be a fairly simple task. I've tried various iterations of this code and nothing works. I did some digging and I'm concerned that perhaps because Aspell is interactive, I need to use something like Expect, but I cannot figure out how to use it. Nor am I sure that it is actually the solution to my problem. I also think ^D should be an appropriate replacement for CTRL+D at the end of the commands, but all I know is it doesn't throw an error. I also tried \cd instead. Whatever it is, there is obviously an issue in either submitting the command or capturing the output.
The complication with using aspell out of a program is that it is an interactive and command-line driver tool, as you suspect. However, there is a simple way to do what you need.
In order to use aspell's command list one needs to pass it words via STDIN, as its man page says. While I find the GNU Aspell manual a little difficult to get going with, passing input to a program via its STDIN is easy enough and we can rewrite the invocation as
echo dad word lkj | aspell list
We get lkj printed back, as due. Now this can run out of a program just as it stands
my $word_list = q(word lkj good asdf);
my $cmd = qq(echo $word_list | aspell list);
my #aspell_out = qx($cmd);
print for #aspell_out;
This prints lines lkj and asdf.
I assemble the command in a string (as opposed to an array) for specific reasons, explained below. The qx is the operator form of backticks, which I prefer for its far superior readability.
Note that qx can return all output in a string, if in scalar context (assigned to a scalar for example), or in a list when in list context. Here I assign to an array so you get each word as an element (alas, each also comes with a newline, so may want to do chomp #aspell_out;).
Comment on a list vs string form of a command
I think that it's safe to recommend to use a list-form for a command, in general. So we'd say
my #cmd = ('ls', '-l', $dir); # to be run as an external command
instead of
my $cmd = "ls -l $dir"; # to be run as an external command
The list form generally makes it easier to manage the command, and it avoids the shell altogether.
However, this case is a little different
The qx operator doesn't really behave differently -- the array gets concatenated into a string, and that runs. The very fact that we can pass it an array is incidental, and not even documented
We need to pipe input to aspell's STDIN, and shell does that for us simply. We can use a shell with command's LIST form as well, but then we'd need to invoke it explicitly. We can also go for aspell's STDIN by means other than the shell but that's more complex
With a command in a list the command name must be the first word, so that "aspell list" from the question is wrong and it should fail (there is no command named that) ... except that in this case it wouldn't (if the rest were correct), since for qx the array gets collapsed into a string
Finally, apsell nicely exposes its API in a C library and that's been utilized for the module you mention. I'd suggest to install it as a user (no privileges needed) and use that.
You should take a step back and investigate if you can install Text::Aspell without administrator privilige. In most cases that's perfectly possible.
You can install modules into your home directory. If there is no C-compiler available on the server you can install the module on a compatible machine, compile and copy the files.

Julia: How to create a symbol inside a function that matches the input variable?

I have a Julia function that takes a few input arguments and uses them to perform multiple operations. In order to get one of those operations to work properly I need to be able to compute a symbol that matches the user input. For example the function looks something like this:
function func(arg1,arg2)
symb_arg1 = ## get the symbol for input into arg1
symb_arg2 = ## get the symbol for input into arg2
println(symb_arg1)
println(symb_arg2)
## Do some operations using arg1, arg2, symb_arg1, symb_arg1
end
I am hoping to achieve the following behavior:
a = 25
b = rand(27,55,18)
func(a,b) ## prints :a and :b
The difficulty here is to get the function to compute a symbol containing the actual name of the variable, rather than the value of the variable. This post provides the following macro that almost does what I want:
macro mymacro(ex)
Expr(:quote,ex) # this creates an expression that looks like :(:(x + 2))
end
This macro works well for doing the following:
a = rand(27,15)
symb_a = #mymacro(a) ## prints :a
However, using this macro inside my function will not produce the desired effect. Specifically, if I define my function as:
function func_bad(arg1,arg2)
symb_arg1 = #mymacro(arg1)
symb_arg2 = #mymacto(arg2)
println(symb_arg1)
println(symb_arg2)
## Do some operations using arg1, arg2, symb_arg1, symb_arg1
end
And then run the commands:
a = 25
b = rand(27,55,18)
func_bad(a,b) ## prints :arg1 and :arg2 (instead of the desired :a and :b)
Of course, one simple (but not so elegant) solution is to add additional input arguments for the function so that the user is responsible for creating the symbols. However this is more of a last resort. I would prefer the function be able to automatically create the symbols. Any idea as to how I can modify my function or the macro to achieve this behavior?
The simple answer is that this is not possible; there is an abstraction barrier that prevents functions from seeing implementation details of their callers. All they get is the values, which is a crucial property for robust and clear programs.
One thing you could do is write a macro to transform the call site:
#with_syms func(a, b)
into something like
func((:a,a), (:b,b))
passing symbol-value pairs into the function.
Another slightly different design would be to provide macro wrappers for all functions that need this behavior, so that calls would look like #func(a,b). You could factor out the argument list transformation to a helper function; each macro would look like
macro func(args...)
:(func($(pair_with_symbols(args)...)))
end

How to apply MATLAB addpath to non static string?

dir1 = '/tmp1';
dir2 = '/tmp2'
If we do the following
addpath [dir1 dir2];
MATLAB takes '[dir1 dir2]' as the path name to add. We can do the following
eval(sprintf(...
'addpath %s;', ...
[dir1 dir2]));
I was wondering if there is any better way. Thank you,
A very simple way to achieve what you want is to call:
addpath(fullfile(dir1,dir2));
Fullfile will take care of adjusting the string to be a proper folder name (under both Windows and Unix) as in:
fullfile('foo','bar') % returns foo/bar
fullfile('foo/','bar') % returns foo/bar
To add files recursively just do:
pathsToAdd = genpath(fullfile(dir1,dir2));
addpath(pathsToAdd);
The general issue that you are having is that MATLAB has two ways of calling commands. The first does not use an explicit function call function() but rather just multiple inputs on the command line separated by a space:
addpath directory1 directory2
As you know this will add both directory1 and directory2 to the path.
What is happening here is that MATLAB converts all of the inputs to strings implicitly and passes them to the addpath function. The explicit equivalent is
addpath('directory1', 'directory2')
As you can see, internally MATLAB calls addpath like a normal function with input parameters, and as such you can pass it variables rather than string literals:
dir1 = 'directory1';
dir2 = 'directory2';
addpath(dir1, dir2);
This is why you are seeing an issue with:
addpath [dir1 dir2]
Because, as written, [dir1 dir2] is convert to a string (implicitly) since it was passed using the function parameter1 parameter2 syntax rather than the explicit function syntax.
Also, be careful because [dir1, dir2] doesn't do what you think it does. What it actually does it appends the strings dir1 and dir2 and would result in:
[dir1, dir2]
/tmp1/tmp2
If that is what you expect, then use fullfile rather than basic horizontal concatenation to ensure you have the proper file separators, etc.
addpath(fullfile(dir1, dir2));
You will actually see the implicit syntax in many MATLAB functions that accept only strings as input parameters. It is important to know, though, that you can always use the explicit function call function() instead to pass input strings which may be stored in variables.

Extract to an OCaml file by using "Recursive Extraction" in Coq

I want to extract a function foo in Coq to an OCaml file. Because my real function have to use the Recursive Extraction, when I run a program it output the extracted OCaml code on the cmd. But I would like to output it to a file, for example: foo.ml
Recursive Extraction foo.
When I tried:
Recursive Extraction "foo.ml" foo.
or Recursive Extraction foo "foo.ml"
I got an error: Syntax error: "." expected after [vernac:command] (in [vernac_aux]).
My question is: Am I able to extract the function foo to a file by using the Recursive Extraction syntax? Thank you for your help.
According to the manual (http://coq.inria.fr/distrib/V8.4/refman/Reference-Manual027.html), Extraction "foo.ml" foo will extract foo and recursively all its dependencies into foo.ml, i.e. you don't need Recursive in that case, it is only used for extraction on stdout.

read function from text file in matlab

I'm going to read some function from a Unicode text file in matlab and calculate there answer with my own variables. first i use fopen to read the text file, then what should i do to convert each line of that text file to a function? for example the func.txt contains:
(x^2)-3y
sin(x+z)+(y^6)
and i need to write an m.file which read func.txt and process that like this:
function func1[x,y] = (x^2)-3y
function func2[x,y,z] = sin(x+z)+(y^6)
Preamble: if your final aim is to use those functions in matlab (i.e. evaluate them for some values of x,y,...), I would rather suggest the following approach that looks more robust to me.
In principle, in fact, you don't need to manipulate the file funct.txt to evaluate the functions defined therein.
First problem: each line of your file funct.txt must define an inline function.
Say that the first function (i.e., the first line) of the file funct.txt has been copied into a string str,
str = '(x^2)-3y',
you can obtain a function from it using the command inline:
f1 = inline(str,'x','y');
which gives to you (matlab output)
f1 =
Inline function:
f1(x,y) = (x^2)-3y.
Now you can use f1 just calling it as f1(x,y), for whatever values x,y.
Second problem: you have to parse your file funct.txt to obtain the strings str containing the definitions of your functions. That's easier, you may want to consider the function fgets.
Third problem: the functions in funct.txt may depend on 2,3 (or more?) independent variables. As far as I know there is no easy way to parse the string to discover it. Thus, you may want to define each inline function as depending on all your independent variables, i.e.
f1 = inline('(x^2)-3y','x','y','z');
the variable z will play no active role, by the way. Nonetheless, you need to specify a third dummy parameter when you call f1.