Create list from input using interact in Haskell - list

I'm starting out with Haskell and was looking into I/O mechanims. I read up on the interact function which takes a function of type String -> String as parameter. I tried to write a simple program that takes to numbers from stdin and creates a list and prints it line by line.
import Data.List
readIn = sort . map read . words
writeOut = unlines . map show
rangeList [n,m] = [n .. m]
main = interact (writeOut . rangeList . readIn)
For some reason it wont print the numbers. Could you help me out?

interact requires you to input an end-of-file (EOF) to stdin with Ctrl+D (or Ctrl+Z on Windows); when I type that combination, the output appears as required. This is necessary because, as the documentation for interact states, ‘the entire input from the standard input device is passed to [interact] as its argument’; due to this, you need to explicitly signal the place where stdin ends.
(By the way, I’m not even sure how you got your program to compile; GHC gives me lots of ‘ambiguous type’ errors when I try. I had to add type signatures to get it working, at which point I found the solution above to work.)

Related

OCaml string length limitation when reading from stdin\file

As part of a Compiler Principles course I'm taking in my university, we're writing a compiler that's implemented in OCaml, which compiles Scheme code into CISC-like assembly (which is just C macros).
the basic operation of the compiler is such:
Read a *.scm file and convert it to an OCaml string.
Parse the string and perform various analyses.
Run a code generator on the AST output from the semantic analyzer, that outputs text into a *.c file.
Compile that file with GCC and run it in the terminal.
Well, all is good and well, except for this: I'm trying to read an input file, that's around 4000 lines long, and is basically one huge expressions that's a mix of Scheme if & and.
I'm executing the compiler via utop. When I try to read the input file, I immediately get a stack overflow error message. It is my initial guess that the file is just to large for OCaml to handle, but I wasn't able to find any documentation that would support this theory.
Any suggestions?
The maximum string length is given by Sys.max_string_length. For a 32-bit system, it's quite short: 16777211. For a 64-bit system, it's 144115188075855863.
Unless you're using a 32-bit system, and your 4000-line file is over 16MB, I don't think you're hitting the string length limit.
A stack overflow is not what you'd expect to see when a string is too long.
It's more likely that you have infinite recursion, or possibly just a very deeply nested computation.
Well, it turns out that the limitation was the amount of maximum ram the OCaml is configured to use.
I ran the following command in the terminal in order to increase the quota:
export OCAMLRUNPARAM="l=5555555555"
This worked like a charm - I managed to read and compile the input file almost instantaneously.
For reference purposes, this is the code that reads the file:
let file_to_string input_file =
let in_channel = open_in input_file in
let rec run () =
try
let ch = input_char in_channel in ch :: (run ())
with End_of_file ->
( close_in in_channel;
[] )
in list_to_string (run ());;
where list_to_string is:
let list_to_string s =
let rec loop s n =
match s with
| [] -> String.make n '?'
| car :: cdr ->
let result = loop cdr (n + 1) in
String.set result n car;
result
in
loop s 0;;
funny thing is - I wrote file_to_string in tail recursion. This prevented the stack overflow, but for some reason went into an infinite loop. Oh, well...

Retrieve all records from universe database using universe basic subroutine

I just want to know that how to retrieve all the record from universe database table using universe basic subroutine.I am new in universe.
Perhaps something like this in the unibasic
OPEN "filename" to FIL ELSE STOP 201,"cannot open filename"
EXECUTE "SELECT filename"
LOOP WHILE READNEXT ID
READ REC FROM FIL,ID ELSE REC = ""
* you now have the entire row in REC
REPEAT
Can you provide more information on what you are trying to do?
Having a subroutine call return the entire contents of a UniVerse file could return a large amount of data. I would expect you would be better off only returning a subset of the items so the calling routine can process a bit at a time.
New content based on comment:
Ok, since you mentioned a type 19 file, I assume you want to read one file from the directory/folder the file points to.
In your subroutine, you can use OPEN on the type 19 file, and use the READ command to read the file. ( Note that you can also use READU, READL, MATREAD, MATREADU, or MATREADL to get the entire file in the directory/folder, depending on if/how you want to lock the item and if you want the data in a dynamic or dimensioned array. If you only need a specific attribute you can then use READV, READVL or READVU commands.
Or, since this is a type 19 file, you can use sequential reads. Open the file with OPENSEQ and read with the READSEQ or READBLK command.
There is an article and sample code on GitHub on how to execute U2 UniVerse Subroutine.
Execute Rocket MV U2 Subroutine Asynchronously using C# (async\await) and U2 Toolkit for .NET. Convert Subroutine Multi-Value Output to Json/Objects/DataTable
These sample code are based on C# (async\await), but you can use for synchronous programming as well with little code tweak.
For article:
Go to this link :
https://github.com/RocketSoftware/multivalue-lab/tree/master/U2/Demos/U2-Toolkit/AsyncAwait/Execute_Subroutine_Async
Read ‘Subroutine-Async.docx’ file.
Sample Code for this article on GitHub
Go to this link :
https://github.com/RocketSoftware/multivalue-lab/tree/master/U2/Demos/U2-Toolkit/AsyncAwait/Execute_Subroutine_Async
OPEN '',FILENAME TO F.FILE ELSE STOP
SELECT F.FILE
LOOP
READNEXT K.FILE ELSE EXIT
READ R.FILE FROM F.FILE, K.FILE ELSE NULL
PRINT R.FILE
REPEAT
PRINT "All over Red Rover"
Filename should be in quotes, i.e "MYFILE" or 'MYFILE'
The loop will repeat till all records have been read and will then exit.

C++ Primer 1.4.4 — Importance of EOF and how to write in a code that will end without EOF?

Referring to two questions:
Incorrect output from C++ Primer 1.4.4
Confused by control flow execution in C++ Primer example
My question is answered in both of those posts, but I want to delve further.
First, I know this is only the beginning, but let's say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a EOF? I can't expect someone running my program to know that they need to hit Control-Z.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
Also one guy in those questions somewhat answered the importance of EOF, but how come the program doesn't even post the final cnt - 1?
Let's say I do the numbers 10 10 10 20 20 20. Without EOF, this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
lets say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a eof? I can't expect someone running my program to know that they need to hit ctrl + z.
You could either tell the user explicitly to do a specific action to end input or the design of the window itself could tell the user the information implicitly. For instance, a dialog box could ask the user to enter input and click an OK button when done.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
It seems like you would rather use a newline character to terminate your input. An example of this usage could be std::getline. Instead of writing
while (std::cin >> val)
you could instead use
std::string line;
if (std::getline(std::cin,line))
and assume that your user's input only consists of one line of values. There are plenty of other ways to similarly achieve this task depending on how you want to constrain the user's input.
Let's say I do the numbers 10 10 10 20 20 20. WIthout eof this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
Without the eof your program is still executing the while (std::cin >> val) loop since std::cin >> val has not yet received invalid input.
Since the line
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
occurs after that while loop finishes execution, you don't (yet) see any information about the three 20's in the input.
When you are reading a sequence of inputs you'll need some indication when your down. That could be a sentinel value ("enter 999 to stop reading"; you'd need to detect that while reading), an invalid input ("enter X to stop reading"; when reading an int the value X is illegal and causes the stream to got into failure mode, i.e., have std::ios_base::failbit set), or the more conventional "there isn't anything more to read". For a file, the last conditions is straight forward. When reading data from the console you'll either need to teach people how to terminate the input or you'll need to use a different approach.
If you want to intercept any keypressed and react on them directly you may do so, too. You could, e.g., use ncurses and control your input via that. You could also set the concole to non-buffering (on POSIX systems using tcgetattr() and tcsetattr() to clear the ICANON flag) and deal directly with all key presses to decide whether you want to continue reading or not.
Although I'm certainly up to doing fancy I/O stuff I normally don't bother: users will understand the "end of input" character and just deal with it. That is, my input normally looks something like this:
while (in >> whatever_needs_to_be_read) { ... }
... or, if the input is genuinely line oriented
for (std::string line; std::getline(in, line); ) { ... }
The function doing this input will then be called with a suitable std::istream which may be std::cin although I have typically some way to also read from a file (in addition to the shell-privided input redirection).
BTW, despite some indications in the questions referenced, "EOF" is not a character being read. It is a character entered, though (normally). ... and it is quite conventional to "know" the end of input character (on POSIX systems a ctrl-D and on Windows a ctrl-Z). You can use other indicators, e.g., the "interrupt" (ctrl-C) but that takes more work and doesn't integrate nicely with stream. To use the interrupt chacter you'd need to setup a signal handler for SIGINT and deal with that. One slightly annoying part of doing so is that if you get it wrong you'll need to find a different way to kill the program (e.g. on POSIX using ctrl-Z to put the process to sleep and kill it via a harsher signal).

Pre-assign parameter in script

Actually I have trouble naming the title of this post. Because I don't know how to summarize my meaning in a professional way. But I'll explain my question as below:
I'm running a program written by C++, command is:
./VariationHunter_SC
Then it'll let you type in many parameters:
Please enter the minimum paired-end insert size:
Please enter the maximum paired-end insert size:
Please enter the pre-processing mapping prune probability:
Please enter the name of the input file:
Please enter the minimum support for a cluster:
Obviously I need to type in such parameters one by one to run the program; But I have thousands of such jobs, and need to pre-assign such parameters in script, and submit script to computer.
So how can I do that?
thx
Edit
so how can I make parameter-list?
Just like below?:
140
160
0
mrfast.vh
1
Seems the program cannot recognize these numbers, and distribute numbers..
This depends on how the program actually reads the data that you type in - it's likely that its reading stdin, so you could use separate files with the parameters and pass them in via redirection: ./VariationHunter_SC < parameter-file
It's also possible that the program will accept parameters on the command line, but there's no way of really knowing that (or how) except by whatever documentation the program might come with (or by reading the source code, if it's available and there is no other accurate docs).
Simply use the piping character to pipe the contents of a file to your program
example, in a windows command shell:
echo "asdf" | pause
This will pass "asdf" to the pause program. As a result, pause will print a "Press any key to continue" message, then imediately continue because it will receive the "asdf" string as a response.
So, overall, write or use a program that outputs the contents of your file. Call it, then pipe its output to the program that needs the input.
The unix cat command is such a command that writes the contents of a file to output, or to the input of another executable if you are piping the output.

Calling Mathematica from OCaml program

I am writing OCaml code. In part of it, I want to examine whether two arithmetic expression are equal (like x+2+y == x+2*y-y+2). Implemeting this in mathematica is straightforward, so all I want some help on executing Mathematica and get the result back in OCaml. My OS platform is Linux.
Cheers,
Z.
You may be able to use something along the lines of this:
let channel_to_mathematica, channel_from_mathematica = open_process "mathematica"
in
Printf.fprintf channel_to_mathematica "Tell me if this is equal ...\n";
let answer_from_mathematica = Scanf.fscanf channel_from_mathematica ...
in
...
Documentation of open_process here
Documentation of module Scanf here
A very general answer is to write a command-line Mathematica script that takes 2 expressions (either on the command line or stdin) and outputs whether they are equal.
Then in OCaml simply call that program with a system call.
As for writing such a command-line Mathematica script, I recommend MASH (disclosure: I made MASH):
Call a Mathematica program from the command line, with command-line args, stdin, stdout, and stderr