How to execute octave code line-by-line - eval

If I start an octave interactive shell, I can type:
octave:1> function y = foo(x)
> y = x + 2;
> endfunction
octave:2> foo(7)
ans = 9
The interpreter knows to wait for the rest of the function definition.
However, if I do
octave:1> eval("function y = foo(x)");
octave:2> eval("y = x + 2;");
octave:3> eval("endfunction");
it evaluates each line as if it were alone. So it defines a function foo which does nothing, and gives errors for the second two lines.
Is there any way to get eval to operate the same as the interpreter? Ultimately, I would like to create an octave script which executes another script, but is able to do other things in between. Is there any way to tell eval to wait for the rest of the command (the way the interactive environment does)? Alternatively, is there a way to feed commands to the interactive interpreter programmatically?
Thank you.

To answer your exact question, I see two immediate ways to do it:
octave> eval ("function y = foo(x) ...
y = x + 2; ...
endfunction")
octave> eval ("function y = foo(x)\n y = x + 2;\n endfunction")
The thing is that you can't split each line in multiple evals, it doesn't make sense. You want to pass a single string with all of the code. Also, you can use the source function to execute code from other files.
Without knowing all the details of what're you're trying to do, I'm guessing you could have your code use input to wait for input from the other code. Or just turn your other script into functions, and call them from your main script.

Related

How to use IDL's min() function's min_subscript argument in for loop?

I have experience in python but am new to IDL. I am trying to write a function that will return two bins. I want to use the min function to get my bin edges. My issue is that I am trying to use the min_subscript argument to denote each bin edge, and I can't figure out how to do this in a for loop. I want to write my code so that each loop has 2 different min_subscript variables (the two edges of the bin), and these variables are written into their own arrays. Here is my code:
FUNCTION DBIN, radius, data, wbin, radbin, databin
FOR i = 0, N_ELEMENTS(radius)-1 DO BEGIN
l = lonarr(N_ELEMENTS(radius))
m = lonarr(N_ELEMENTS(radius))
junk1 = min(abs(radius - radius[i]), l[i])
junk2 = min(abs(radius - (radius[i] + wbin)), m[i])
radbin = lonarr(N_ELEMENTS(radius))
radbin[i] = radius[l[i]:m[i]]
databin = lonarr(N_ELEMENTS(data))
databin[i] = total(data[l[i]:m[i]])
ENDFOR
END
wbin is the desired bin width. The junk variables only exist for the purpose of getting the min_subscripts at those locations. The min_subscripts are the l[i]'s and the m[i]'s.
I appreciate any help!!
The min_subscript argument is trying to pass a value back to you, so you must pass a "named variable" to it. Named variables have pass by reference behavior. So you have to do it in two steps, something like:
junk1 = min(abs(radius - radius[i]), li)
l[i] = li
Above, li is a named variable, so it can receive and pass back the value. Then you can put it in your storage array.

Perl IO::Pipe does not work within arrays

im trying the following:
I want to fork multiple processes and use multiple pipes (child -> parent) simultaneously.
My approach is to use IO::Pipe.
#!/usr/bin/perl
use strict;
use IO::Pipe;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my #ua_processes = (0..9);
my $url = "http://<some-sample-textfile>";
my #ua_pipe;
my #ua_process;
$ua_pipe[0] = IO::Pipe->new();
$ua_process[0] = fork();
if( $ua_process[0] == 0 ) {
my $response = $ua->get($url);
$ua_pipe[0]->writer();
print $ua_pipe[0] $response->decoded_content;
exit 0;
}
$ua_pipe[0]->reader();
while (<$ua_pipe[0]>) {
print $_;
}
In future i want to use multiple "$ua_process"s in an array.
After execution i got the following errors:
Scalar found where operator expected at ./forked.pl line 18, near "] $response"
(Missing operator before $response?)
syntax error at ./forked.pl line 18, near "] $response"
BEGIN not safe after errors--compilation aborted at ./forked.pl line 23.
If i dont use arrays, the same code works perfectly. It seems only the $ua_pipe[0] dont work as expected (together with a array).
I really dont know why. Anyone knows a solution? Help would be very appreciated!
Your problem is here:
print $ua_pipe[0] $response->decoded_content;
The print and say builtins use the indirect syntax to specify the file handle. This allows only for a single scalar variable or a bareword:
print STDOUT "foo";
or
print $file "foo";
If you want to specify the file handle via a more complex expression, you have to enclose that expression in curlies; this is called a dative block:
print { $ua_pipe[0] } $response-decoded_content;
This should now work fine.
Edit
I overlooked the <$ua_pipe[0]>. The readline operator <> also doubles as the glob operator (i.e. does shell expansion for patterns like *.txt). Here, the same rules as for say and print apply: It'll only use the file handle if it is a bareword or a simple scalar variable. Otherwise, it will be interpreted as a glob pattern (implying stringification of the argument). To disambiguate:
For the readline <>, we have to resort to the readline builtin:
while (readline $ua_pipe[0]) { ... }
To force globbing <>, pass it a string: <"some*.pattern">, or preferably use the glob builtin.

How to call an m file from another m file in MATLAB and retrieve an output?

I know this is a simple question, but for some reason I can't find a straight answer that works no matter where I look.
Basically, I have 4 values that were found in one m file, and I want to run them through a separate m file and retrieve the output from it.
I tried something like these, but none worked:
result = generate(nrow,ncol,a,b);
function result = generate(nrow,ncol,a,b);
result = #generate(nrow,ncol,a,b);
The final value in the m file "generate" is called result, and I'm trying to carry that across to my initial m file.
Any advice as to what I'm doing wrong would be greatly appreciated! Please and thank you
if your file generate.m defines a function it should have itself the following structure (which takes into account the fact that you have four returned values)
function [ret1 ret2 ret3 ret4] = generate(nrow,ncol,a,b)
.... % # Some processing of yours
ret1 = ... ; % # Returned values are eventually set
ret2 = ... ;
ret3 = ... ;
ret4 = ... ;
end
The function should be called (e.g. in your main script) as
[ret1 ret2 ret3 ret4] = generate(nrow,ncol,a,b);
now you have the variables ret1,ret2,ret3,ret4 available in the caller scope.
Be aware that the file generate.m must be in the current matlab PATH.

simple Haskell loop

I just started learning Haskell, but the absence of loops is infinitely frustrating right now. I figured out how to write loops for functions. My problem, however, is that I want to output some results while iterating the loop. It seems that I have to use debug to perform this simple task.
So right now I would just appreciate an example of how to print out a string 10 times in the main structure.
In other words, I want to do this 10 times:
main = do
putStrLn "a string"
Thanks. I feel this will be very illuminating for my task.
You could define a recursive function that prints "a string" n times (n being the parameter of the function), like this:
printStringNTimes 0 = return ()
printStringNTimes n =
do
putStrLn "a string"
printStringNTimes (n-1)
main = printStringNTimes 10
A somewhat more general approach would be to define a function that repeats any IO action n times:
repeatNTimes 0 _ = return ()
repeatNTimes n action =
do
action
repeatNTimes (n-1) action
main = repeatNTimes 10 (putStrLn "a string")
The above function already exists in Control.Monad under the name replicateM_.
Well Haskell's IO is a bit tricky when you're just starting out since it's based on monads.
Your problem though has a simple solution:
main = replicateM_ 10 $ putStrLn "a string"
This is using the combinator replicateM_ from Control.Monad
It has lots of useful functions for composing and executing monadic actions.
I am also a beginner of Haskell, and I have a solution that is less elegant and yet is pragmatically useful.
main = do
putStr result
where
string = "a string"
result = concat [string ++ "\n" | i <- [1,2..10]]
So here, we have defined a list, the elements of which are the strings that you want to print out followed by a new line character.
I think the most imperative looking form of doing a for loop is:
for list action = mapM_ action list
main :: IO Int
main = do
for [0..10] (\ i -> do
print(i^2)
)
return 0
This actually looks pretty much like C code to me.
Doing something like to this allows you to loop a specific function, making it more reusable (instead of writing it out for each new thing you want to loop).
loop :: Int -> (IO()) -> IO()
loop 0 _ = return ()
loop n f =
do
f
loop (n - 1) f
Examples:
main = do
loop 5 (do
putStr "hello "
putStrLn "there")
main = do
loop 3 (do
loop 4 (putStrLn "Hi")
putStrLn ""
)
my solution:
n = 10
doSomething () = putStrLn "a string"
main = sequence (replicate n (doSomething()))
sequence: sequentially solve each IO a in a list
replicate n ele: build a list which repeats ele for n times, like take n (repeat ele)

Loops' iterating in ANTLR

I'm trying to make a Pascal interpreter using ANTLR and currently have some troubles with processing loops while walking the AST tree.
For example for loop is parsed as:
parametricLoop
: FOR IDENTIFIER ASSIGN start = integerExpression TO end = integerExpression DO
statement
-> ^( PARAMETRIC_LOOP IDENTIFIER $start $end statement )
;
(variant with DOWNTO is ignored).
In what way can I make walker to repeat the loop's execution so much times as needed? I know that I should use input.Mark() and input.Rewind() for that. But exactly where should they be put? My current wrong variant looks so (target language is C#):
parametricLoop
:
^(
PARAMETRIC_LOOP
IDENTIFIER
start = integerExpression
{
Variable parameter = Members.variable($IDENTIFIER.text);
parameter.value = $start.result;
}
end = integerExpression
{
int end_value = $end.result;
if ((int)parameter.value > end_value) goto EndLoop;
parametric_loop_start = input.Mark();
}
statement
{
parameter.value = (int)parameter.value + 1;
if ((int)parameter.value <= end_value)
input.Rewind(parametric_loop_start);
)
{
EndLoop: ;
}
;
(Hope everything is understandable). The condition of repeating should be checked before the statement's first execution.
I tried to play with placing Mark and Rewind in different code blocks including #init and #after, and even put trailing goto to loops head, but each time loop either iterated one time or threw exceptions like Unexpected token met, for example ':=' (assignement). I have no idea, how to make that work properly and can't find any working example. Can anybody suggest a solution of this problem?
I haven't used ANTLR, but it seems to me that you are trying to execute the program while you're parsing it, but that's not really what parsers are designed for (simple arithmetic expressions can be executed during parsing, but as you have discovered, loops are problematic). I strongly suggest that you use the parsing only to construct the AST. So the parser code for parametricLoop should only construct a tree node that represents the loop, with child nodes representing the variables, conditions and body. Afterwards, in a separate, regular C# class (to which you provide the AST generated by the parser), you execute the code by traversing the tree in some manner, and then you have complete freedom to jump back and forth between the nodes in order to simulate the loop execution.
I work with ANTLR 3.4 and I found a solution which works with Class CommonTreeNodeStream.
Basically I splitted off new instances of my tree parser, which in turn analyzed all subtrees. My sample code defines a while-loop:
tree grammar Interpreter;
...
#members
{
...
private Interpreter (CommonTree node, Map<String, Integer> symbolTable)
{
this (new CommonTreeNodeStream (node));
...
}
...
}
...
stmt : ...
| ^(WHILE c=. s1=.) // ^(WHILE cond stmt)
{
for (;;)
{
Interpreter condition = new Interpreter (c, this.symbolTable);
boolean result = condition.cond ();
if (! result)
break;
Interpreter statement = new Interpreter (s1, this.symbolTable);
statement.stmt ();
}
}
...
cond returns [boolean result]
: ^(LT e1=expr e2=expr) {$result = ($e1.value < $e2.value);}
| ...
Just solved a similar problem, several points:
Seems you need to use BufferedTreeNodeStream instead of CommonTreeNodeStream, CommonTreeNodeStream never works for me (struggled long time to find out)
Use seek seems to be more clear to me
Here's my code for a list command, pretty sure yours can be easily changed to this style:
list returns [Object r]
: ^(LIST ID
{int e_index = input.Index;}
exp=.
{int s_index = input.Index;}
statements=.
)
{
int next = input.Index;
input.Seek(e_index);
object list = expression();
foreach(object o in (IEnumerable<object>)list)
{
model[$ID.Text] = o;
input.Seek(s_index);
$r += optional_block().ToString();
}
input.Seek(next);
}

Resources