Write output line in standard output in Erlang - erlang

I would like to know if there is any function in Erlang for writing
io:format("An output line~n").
in the standard output, without having to write ~n every time, i.e. an equivalent to Java's
System.out.println("An output line");
I mean an already existing Erlang function. I know if it doesn't exist what I should do is creating my own function for that:
write_output(Text) ->
io:format("~p~n", [Text]).

No, there is not, but writing one yourself is pretty simple:
myf(FS, Opts) ->
io:format(FS, Opts),
io:nl().

Today, IODevice command is optional for io operations.
io:write(["~cmd1~cmd2",]T)
format, read & write can all be used in one line. as..
io:format(T);
% or
io:write(T);
but if there is a need for the line feed, the author's original code is more accurate
io:format("~p~n",[Number])
if building a function other built-in functions may be used to do the same
io:format(string:concat(integer_to_list(Number),"\n"))

Related

Lua REPL that can auto disambiguate expresssions and statements?

As it is known, Lua 5.3 handles interactive REPL to differentiate expressions and statements this way:
In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.
However, this is not the behavior I want. For example, I have some codes "f()" to evaluate, where f will through error, no matter what happens. it also change the internal state of lua. The above approach will cause bugs because it will change the internal state twice.
So, I'd like to know, is there a way to implement a REPL that auto disambiguate expressions and statements? Do I have to add some syntax analysis to achieve this?
Interpreting code in Lua REPL is a two step process. First you convert the input to a runnable code with loadstring or a similar function. The code has been validated to be correct but didn’t run yet. Then you explicitly invoke it.
fn = loadstring(“return 42”);
fn()
To summarize, parsing and validating code with loadstring() or a similar function is side effect free, as long as you don’t invoke the result.

Evaluate already parsed duration expression

I'm writing a tool which reads go code and parses some duration expressions like: dur := 5 * time.Minute. I already have the parsing step done and got a *ast.BinaryExpr. How can I evaluate this expression and get its value?
Is there something in the toolchain/packages or do I need to go by hand?
I think parser package is the one your looking for.
go also has a package named eval (https://godoc.org/github.com/apaxa-go/eval) that evaluates expressions.
And there are two libraries that might help you down the line.
https://github.com/PaesslerAG/gval
https://github.com/Knetic/govaluate
Gval (Go eVALuate) provides support for evaluating arbitrary expressions, in particular Go-like expressions.
Good luck!

Incremental Parsing from Handle in Haskell

I'm trying to interface Haskell with a command line program that has a read-eval-print loop. I'd like to put some text into an input handle, and then read from an output handle until I find a prompt (and then repeat). The reading should block until a prompt is found, but no longer. Instead of coding up my own little state machine that reads one character at a time until it constructs a prompt, it would be nice to use Parsec or Attoparsec. (One issue is that the prompt changes over time, so I can't just check for a constant string of characters.)
What is the best way to read the appropriate amount of data from the output handle and feed it to a parser? I'm confused because most of the handle-reading primatives require me to decide beforehand how much data I want to read. But it's the parser that should decide when to stop.
You seem to have two questions wrapped up in here. One is about incremental parsing, and one is about incremental reading.
Attoparsec supports incremental parsing directly. See the IResult type in Data.Attoparsec.Text. Parsec, alas, doesn't. You can run your parser on what you have, and if it gives an error, add more input and try again, but you really don't know if the error was an unrecoverable parse error, or just needing for more input.
In your case, usualy REPLs read one line at a time. Hence you can use hGetLine to read a line - pass it to Attoparsec, and if it parses evaluate it, and if not, get another line.
If you want to see all this in action, I do this kind of thing in Plush.Job.Output, but with three small differences: 1) I'm parsing byte streams, not strings. 2) I've set it up to pull as much as is available from the input and parse as many items as I can. 3) I'm reading directly from file descriptos. But the same structure should help you do it in your situation.

Erlang: Compute data structure literal (constant) at compile time?

This may be a naive question, and I suspect the answer is "yes," but I had no luck searching here and elsewhere on terms like "erlang compiler optimization constants" etc.
At any rate, can (will) the erlang compiler create a data structure that is constant or literal at compile time, and use that instead of creating code that creates the data structure over and over again? I will provide a simple toy example.
test() -> sets:from_list([usd, eur, yen, nzd, peso]).
Can (will) the compiler simply stick the set there at the output of the function instead of computing it every time?
The reason I ask is, I want to have a lookup table in a program I'm developing. The table is just constants that can be calculated (at least theoretically) at compile time. I'd like to just compute the table once, and not have to compute it every time. I know I could do this in other ways, such as compute the thing and store it in the process dictionary for instance (or perhaps an ets or mnesia table). But I always start simple, and to me the simplest solution is to do it like the toy example above, if the compiler optimizes it.
If that doesn't work, is there some other way to achieve what I want? (I guess I could look into parse transforms if they would work for this, but that's getting more complicated than I would like?)
THIS JUST IN. I used compile:file/2 with an 'S' option to produce the following. I'm no erlang assembly expert, but it looks like the optimization isn't performed:
{function, test, 0, 5}.
{label,4}.
{func_info,{atom,exchange},{atom,test},0}.
{label,5}.
{move,{literal,[usd,eur,yen,nzd,peso]},{x,0}}.
{call_ext_only,1,{extfunc,sets,from_list,1}}.
No, erlang compiler doesn't perform partial evaluation of calls to external modules which set is. You can use ct_expand module of famous parse_trans to achieve this effect.
providing that set is not native datatype for erlang, and (as matter of fact) it's just a library, written in erlang, I don't think it's feasibly for compiler to create sets at compile time.
As you could see, sets are not optimized in erlang (as any other library written in erlang).
The way of solving your problem is to compute the set once and pass it as a parameter to the functions or to use ETS/Mnesia.

F# interactive development

Coming from a Matlab and R background where the development process is very interactive (select, run selection, fix, select, run selection, fix, etc), I'm trying to figure out how F# handles this style of development, which seems pretty important in scientific applications. Here are few things that just immediately come to mind to somebody new to F#:
Selecting multiple lines gives different results than one line at a time.
let add x y = x + y
add 4.1 2.3
Selecting both lines results in float -> float -> float whereas selecting the first line results in int -> int -> int. More generally, matlab/R users are used to results printing out after each statement, not at the end.
Shadow copying can become burdensome.
let file = open2GBfile('file.txt')
process file
If you run this interactively over and over again, the 2GB file is shadow copied and you will quickly run out of memory. Making file mutable doesn't seem like the appropriate solution, since the final run of the program will never change it.
Given these issues, is it impossible for a fsi.exe based system to support matlab/R style interactive development?
[Edit: I am guessing about 2. Do objects get marked for deletion as soon as they are shadowed?]
I wouldn't expect F# to be a drop-in replacement for Matlab/R, because unlike them, F# is a general purpose programming language. Not everything you need for a specific type of work will be in the standard libraries. But that doesn't mean that the "interactive development" you describe is impossible, it may just require some effort up-front to build the library functions you depend on.
For #1, as was mentioned earlier, adding type annotations is unfortunately necessary in some cases, but also the inline keyword and "hat-types" can give you duck-typing.
For #2, I'm not clear on what your open and process functions do, versus what you want them to do. For example, the open function could:
Read the entire file at once, return the data as an array/list/etc, and then close the file
Return a FileStream object, which you're calling process on but forget to close.
Return a sequence expression so you can lazily iterate over the file contents
Memoize the result of one of the above, so that subsequent calls just return the cached result
One of the gazillion other ways to create an abstraction over file access.
Some of these are better suited for your task than others. Compared to Matlab & R, a general purpose language like F# gives you more ways to shoot yourself in the foot. But that's because it gives you more ways to do everything.
To #1
In FSI, you'll have to type ;; at the end of each statement and get the results directly:
> 1 + 2;;
val it : int = 3
Generally an F#-Codefile should be seen as a collection of individual functions that you have to call and evaluate interactively and not as a series of steps that produce values to be shown.
To #2:
This seems to be a problem of the code itself: Make file a function, so the reading/copying is only done when and where really needed (otherwise the let binding would be evaluated in the beginning).

Resources