Real standard input in Racket - input

It seems that Racket is incapable of reading a string from STDIN.
$ racket
Welcome to Racket v6.4.
-> (define (s) (read-line))
OK, s is an alias for a call to read-line.
-> (printf "You entered: ~a\n" s)
You entered:
Failure: The string is printed, but Racket does not wait for keypress / STDIN / EOF / EOL.
-> (define n (read))
a
-> n
'a
Failure: This makes a call to read and waits for EOF / EOL, then assigns to n, but n is assigned the symbol 'a not the string literal a.
-> (read-line)
""
Failure: calling read-line doesn't wait for STDIN, just returns the empty string.
-> (read-string 5)
asdasdasdasd
"\nasda"
; sdasdasd: undefined;
; cannot reference undefined identifier
; [,bt for context]
Failure: only reads 5 bytes of STDIN, and apparently evals the rest of it... ?
-> (read-string 500000)
asdasd
asdasdaas
a
asdasd
asdasd
asdasd
Failure: doesn't return until exactly 500000 bytes have been read, and doesn't return on EOL.
Somewhat like Python's input() which returns a string when EOL is found, or Factor's readln which does the same, how can I read raw data from the current-input-port?

This is just a limitation of the Racket's REPL's input handling. If you write a standalone program it will work fine.
Here's a quote from the mailing list that explains the problem:
A known limitation. The REPL implemented by plain `racket' does not
separate the input stream for REPL expressions from the program's
input stream.
More details: https://groups.google.com/d/msg/racket-users/0TTsA9-3HDs/9_mMWsgKFOMJ

Related

Emacs call-process stumbles upon supplied args content

I'm puzzled by unexpected behavior of a call-process call.
Here's a little function:
(defun work-in-progress()
"run ledger report and output result in current buffer.
The intention is to run following command (works perfectly from shell):
`ledger -U csv --sort date --file ledger-file child`
where ledger-file is a known and defined variable.
The problem is that the command fails with:
`Error: Illegal option -`
"
(interactive)
(cd ledger-dir)
(setq child "peter")
(setq parms "-U csv --sort date --file")
(setq prog "ledger") ; should be found via path variable or so
(call-process prog nil t t parms ledger-file child)
)
I've played around with the sequence of the ledger command options, but emacs always seems to complain about the first option or all options in the parms variable:
e.g.
(setq parms "--sort date -U csv --file")
results in
Error: Illegal option --sort date -U csv --file
iso
Error: Illegal option -
The ledger cli program isn't fussy about arguments sequence, both described option sequences work perfectly well when calling ledger at the command line.
This truly puzzles me. The documentation reads
call-process program &optional infile destination display &rest args
and infile is set to nil, destination as well as display are t, so why doesn'it grok the content of args variable?
Any help, correction and/or suggestion would be sincerely appreciated!
The tail of the list should be a sequence of strings, each corresponding to one argument.
(setq parms '("-U" "csv" "--sort" "date" "--file"))
(setq prog "ledger")
(apply #'call-process prog nil t t (append parms '(ledger-file child)))
You need apply to make the result of append into a continuation of the static list of arguments to call-process.
I had to guess what ledger-file and child are; if they are not strings, you need to convert them to strings.
To briefly recapitulate how the shell parses arguments, the command line
echo foo "bar $baz" 'quux $baz'
gets turned into the string array
'("echo" "foo" "bar <<value of baz>>" "quux $baz")
(to use a Lispy notation) and passed as arguments to execlp.
The solution is to pass each parameter as a separate string:
(defun work-in-progress()
"run ledger report and output result in current buffer. "
(interactive)
(cd ledger-dir)
(setq child "peter")
(setq prog "ledger") ; should be found via path variable or so
(call-process prog nil t t "--sort" "date" "-U" "csv" "--file" ledger-file child)
)

Why syntax error in this very simple print command

I am trying to run following very simple code:
open Str
print (Str.first_chars "testing" 0)
However, it is giving following error:
$ ocaml testing2.ml
File "testing2.ml", line 2, characters 0-5:
Error: Syntax error
There are no further details in the error message.
Same error with print_endline also; or even if no print command is there. Hence, the error is in part: Str.first_chars "testing" 0
Documentation about above function from here is as follows:
val first_chars : string -> int -> string
first_chars s n returns the first n characters of s. This is the same
function as Str.string_before.
Adding ; or ;; at end of second statement does not make any difference.
What is the correct syntax for above code.
Edit:
With following code as suggested by #EvgeniiLepikhin:
open Str
let () =
print_endline (Str.first_chars "testing" 0)
Error is:
File "testing2.ml", line 1:
Error: Reference to undefined global `Str'
And with this code:
open Str;;
print_endline (Str.first_chars "testing" 0)
Error is:
File "testing2.ml", line 1:
Error: Reference to undefined global `Str'
With just print command (instead of print_endline) in above code, the error is:
File "testing2.ml", line 2, characters 0-5:
Error: Unbound value print
Note, my Ocaml version is:
$ ocaml -version
The OCaml toplevel, version 4.02.3
I think Str should be built-in, since opam is not finding it:
$ opam install Str
[ERROR] No package named Str found.
I also tried following code as suggested in comments by #glennsl:
#use "topfind"
#require "str"
print (Str.first_chars "testing" 0)
But this also give same simple syntax error.
An OCaml program is a list of definitions, which are evaluated in order. You can define values, modules, classes, exceptions, as well as types, module types, class types. But let's focus on values so far.
In OCaml, there are no statements, commands, or instructions. It is a functional programming language, where everything is an expression, and when an expression is evaluated it produces a value. The value could be bound to a variable so that it could be referenced later.
The print_endline function takes a value of type string, outputs it to the standard output channel and returns a value of type unit. Type unit has only one value called unit, which could be constructed using the () expression. For example, print_endline "hello, world" is an expression that produces this value. We can't just throw an expression in a file and hope that it will be compiled, as an expression is not a definition. The definition syntax is simple,
let <pattern> = <expr>
where is either a variable or a data constructor, which will match with the structure of the value that is produced by <expr> and possibly bind variable, that are occurring in the pattern, e.g., the following are definitions
let x = 7 * 8
let 4 = 2 * 2
let [x; y; z] = [1; 2; 3]
let (hello, world) = "hello", "world"
let () = print_endline "hello, world"
You may notice, that the result of the print_endline "hello, world" expression is not bound to any variable, but instead is matched with the unit value (), which could be seen (and indeed looks like) an empty tuple. You can write also
let x = print_endline "hello, world"
or even
let _ = print_endline "hello, world"
But it is always better to be explicit on the left-hand side of a definition in what you're expecting.
So, now the well-formed program of ours should look like this
open Str
let () =
print_endline (Str.first_chars "testing" 0)
We will use ocamlbuild to compile and run our program. The str module is not a part of the standard library so we have to tell ocamlbuild that we're going to use it. We need to create a new folder and put our program into a file named example.ml, then we can compile it using the following command
ocamlbuild -pkg str example.native --
The ocamlbuild tool will infer from the suffix native what is your goal (in this case it is to build a native code application). The -- means run the built application as soon as it is compiled. The above program will print nothing, of course, here is an example of a program that will print some greeting message, before printing the first zero characters of the testing string,
open Str
let () =
print_endline "The first 0 chars of 'testing' are:";
print_endline (Str.first_chars "testing" 0)
and here is how it works
$ ocamlbuild -package str example.native --
Finished, 4 targets (4 cached) in 00:00:00.
The first 0 chars of 'testing' are:
Also, instead of compiling your program and running the resulting application, you can interpret your the example.ml file directly, using the ocaml toplevel tool, which provides an interactive interpreter. You still need to load the str library into the toplevel, as it is not a part of the standard library which is pre-linked in it, here is the correct invocation
ocaml str.cma example.ml
You should add ;; after "open Str":
open Str;;
print (Str.first_chars "testing" 0)
Another option is to declare code block:
open Str
let () =
print (Str.first_chars "testing" 0)

Racket equivalents of python's __repr__ and __str__?

In python objects, overriding the methods __repr__ and __str__ of an object allows one to provide "unambiguous" and "human-readable" representations of the object, respectively. How does one achieve similar behavior in Racket?
I came across the printable<%> interface here, which seems like it should be usable for this purpose, but I haven't been able to get it to work quite as I expect it to. Building on the standard "fish" example from the docs:
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
This is the output I get:
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
So the question is threefold:
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the write function internally?
Is this the right construct to use for this purpose at all? If not, is there one / what is it?
As for
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
You have accidently used print in write, so writing the value, will first print the value.
(define/public (custom-write port)
(print "Write called!"))
A similar problem is present in display.
Also remember to print/write/display to the proper port.
Try
#lang racket
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print (~a "Print " current-size "\n") port))
(define/public (custom-write port)
(write (~a "Write " current-size "\n") port))
(define/public (custom-display port)
(display (~a "Display " current-size "\n") port))))
In the repl you will see:
> (define f (new fish% [size 10]))
> f
"Print 10\n"
> (display f)
Display 10
> (write f)
"Write 10\n"
Another answer has already helped you find the problem in your code—you need to use the port given as an argument, not the implicit (current-output-port)—but the explanation isn't quite right. To tackle your questions in reverse order:
Is this the right construct to use for this purpose at all? If not, is there one / what is it?
Yes, printable<%> is the right construct to use to customize printing of a class-based object. More generally, a struct type that is not a class can customize printing for instance through the gen:custom-write generic interface or the low-level prop:custom-write struct type property, which is used to implement printable<%>.
What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the write function internally?
The methods should actually do the side-effect of performing IO on the port they are given as an argument. They should use the corresponding function (e.g. write for custom-write, print for custom-print) internally for recursively printing/writing/displaying values in fields. On the other hand, when directly emitting particular characters, they should generally use functions like write-char, write-string, or printf. The docs for gen:custom-write give an example of a tuple datatype that prints as <1, 2, "a">: it uses write-string for the angle-brackets and commas, but recursive print/write/display for the elements of the tuple.
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
This is the most involved part of your question. Printing in Racket is customizable through several hooks: for a few examples, see current-print, port-write-handler, global-port-print-handler, and make-tentative-pretty-print-output-port. Many of these customization hooks use intermediate ports in the process of producing output.
One thing that is not a part of the explanation is the fact that you used print in your implementation, particularly as print is bound to the normal Racket function by lexical scope, not to a method of your object.
As an illustration, consider the following adaptation of your example, which reports to the (current-output-port) the identity of the port given as an argument to the method:
#lang racket
(define report
(let ([next-id 0]
[id-cache (make-hash)])
(λ (op port)
(printf "~a ~a ~v\n"
op
(hash-ref id-cache
port
(λ ()
(define id next-id)
(hash-set! id-cache port id)
(set! next-id (add1 next-id))
id))
port))))
(define fish%
(class* object% (printable<%>)
(super-new)
;; implement printable interface
(define/public (custom-print port quoting-depth)
(report "custom-print " port))
(define/public (custom-write port)
(report "custom-write " port))
(define/public (custom-display port)
(report "custom-display" port))))
(define f (new fish%))
f
(print f)
(newline)
(display f)
(newline)
(write f)
In DrRacket, this generates the output:
custom-display 0 #<output-port:null>
custom-display 1 #<output-port:null>
custom-print 2 #<printing-port>
custom-display 3 #<output-port:null>
custom-display 4 #<output-port:null>
custom-print 5 #<printing-port>
custom-display 6 #<output-port:null>
custom-display 7 #<printing-port>
custom-display 8 #<output-port:null>
custom-write 9 #<printing-port>
while at the command line, the output is:
$ racket demo.rkt
custom-write 0 #<output-port:null>
custom-print 1 #<output-port:redirect>
custom-write 2 #<output-port:null>
custom-print 3 #<output-port:redirect>
custom-display 4 #<output-port:null>
custom-display 5 #<output-port:redirect>
custom-write 6 #<output-port:null>
custom-write 7 #<output-port:redirect>

Rakudo Perl 6: clear screen while using Readline module

Here's my test program:
use Readline;
shell 'clear';
my $r = Readline.new;
loop {
my $a = $r.readline("> ");
{say ''; last} if not defined $a;
$r.add-history( $a );
say $a;
}
After I enter any string, it exits with the following message:
> abc
Internal error: unhandled encoding
in method CALL-ME at /opt/rakudo-pkg/share/perl6/sources/24DD121B5B4774C04A7084827BFAD92199756E03 (NativeCall) line 587
in method readline at /home/evb/.perl6/sources/D8BAC826F02BBAA2CCDEFC8B60D90C2AF8713C3F (Readline) line 1391
in block <unit> at abc.p6 line 7
If I comment the line shell 'clear';, everything is OK.
This is a bit of a guess, but I think when you tell your shell to clear the screen, it's sending a control character or control sequence as input to the terminal emulator. Readline is reading from that same stream, and those characters end up at the beginning of your "line" when you try to read a line. Those characters aren't valid UTF-8 (the default encoding) and so can't be interpreted as a string. You'll know more if you open the text files in the stack trace and look at the relevant line numbers.
You can try calling reset-terminal or reset-line-state to see if you can get rid of that character. What I would do in a low level programming language is to do a nonblocking read of the input (without converting it into a string), but I can't find the API for that in the Perl 6 library.

How to implement a process that receives two messages and adds the two numbers together in Erlang?

The process adder2, as implemented in Erlang, has the signature:
adder2 (In0, In1, Kill, Out) ->
...
The three messages that can be sent to this process are as indicated in the
diagram: {In0, Msg}, {In1, Msg} and {Kill}, where In0, In1
and Kill are provided in the function’s arguments and identify the type of
message.
The process itself waits for both the input messages, where Msg represents
an integer value which is communicated. Once both inputs have been
received, it outputs the sum of these to the process identified as Out.
At any
time whilst waiting for the inputs it may be sent a Kill message to which it
should respond by terminating normally.
Provide an implementation of this process using the signature given above.
I understand that there needs to be a receive expression for In0, In1 and Kill messages. However I do not know the correct syntax to allow the messages to be received in any order, can anyone assist me with this?
I am also unsure of the correct syntax for adding the two values together.
Outputting them would require them to be assigned to a result value, and sent to the Out process, such as Out ! Result.
First, all variables start with an uppercase so Erlangers would read {In0, Msg} as a tuple where both elements are variable. If you mean message with first element of fixed value you should write {in0, Msg} or {'In0', Msg} where the first element is an atom 'in0' or 'In0'. There can be variant of your adder2 with configurable the first element of the message but it will be more complicated. So if we expect messages {in0, Msg}, {in1, Msg} and kill (It doesn't have to be a one-element tuple.) the solution can be:
-module(adder2).
-export([start/1]).
start(Out) ->
spawn(fun() -> adder2(Out) end).
adder2(Out) ->
adder2(undefined, undefined, Out).
adder2(undefined, In1, Out) ->
wait(undefined, In1, Out);
adder2(In0, undefined, Out) ->
wait(In0, undefined, Out);
adder2(In0, In1, Out) ->
Out ! In0 + In1,
adder2(Out).
wait(In0, In1, Out) ->
receive
{in0, Msg} when is_integer(Msg) ->
adder2(Msg, In1, Out);
{in1, Msg} when is_integer(Msg) ->
adder2(In0, Msg, Out);
kill ->
ok; % last in a chain of tail recursive functions so exit normal
Msg ->
io:format("~p: Unknown message: ~p~n", [self(), Msg]),
adder2(In0, In1, Out)
end.
Shell session example:
1> c(adder2).
{ok,adder2}
2> P = adder2:start(self()).
<0.43.0>
3> link(P).
true
4> process_flag(trap_exit, true).
false
5> P ! {foo, bar}.
<0.43.0>: Unknown message: {foo,bar}
{foo,bar}
6> P ! {in0, 2.3}.
<0.43.0>: Unknown message: {in0,2.3}
{in0,2.3}
7> P ! {in0, 2}.
{in0,2}
8> P ! {in1, 3}.
{in1,3}
9> flush().
Shell got 5
ok
10> P ! {in1, 2}.
{in0,2}
11> P ! {in1, 3}. % rewrite previous value in wait/3
{in0,3}
12> P ! {in0, 4}.
{in1,4}
13> flush().
Shell got 7
ok
14> P ! {in1, 3}.
{in1,3}
15> P ! kill.
kill
16> flush().
Shell got {'EXIT',<0.43.0>,normal}
ok