Why does array "each" do not work anymore in Crystal 1.3.0? What should I use instead? - crystal-lang

The code below does not print the elements of the array. Why is that?
array = [1, 2, 3]
array.each do |x|
puts x
end
array.each { |x| puts x }
Crystal Play Output
It used to work in previous versions. I know Crystal is not Ruby, but the code above works in Ruby. What is the best practice to iterate through an array in Crystal? And why did the Crystal developers decide to make Crystal incompatible with Ruby in such a basic scenario?

Short answer: click "SHOW OUTPUT" below right-hand side box.
There is an apparent difference between the local version of Crystal Playground you get from running crystal play and the one running at play.crystal-lang.org. The code works, but the presentation of the results is different.

The crystal playground cannot execute this code for some reason.
Don't use the crystal playground. It is currently close to useless.
Put the code in a file and do:
crystal each.cr
And you will see the array elements.

Related

Smalltalk (Pharo) How to interface with the user simply

I stumbled upon Smalltalk and further downloaded Pharo, because it was recommended. My first impression is very positive. I wanted to port some simple programs I have written in C++ (my main language), so I can get a feel for Smalltalk.
However, I realized I can't find a simple way to just get some input from the user, e.g. I want to create a console calculator with a REPL loop, but I can't find a way to do this in Pharo. I don't want a gui with buttons, because that is just slow and inconvenient.
Could someone please point out to me how to do simple stuff in Smalltalk, like have the user enter 10 numbers or a command etc.? Do I have to use a different implementation? I'm aiming at std::cin/cout or python's print/input
I know Transcript show:, but that only covers the output portion.
Thanks in advance!
Getting input from the user is easy, but emulating a line-based console not so much. At least it would be more cumbersome than relying on the GUI, which is not really so slow and inconvenient after all.
The closest input equivalent to Transcript show: would be:
UIManager default request: 'Title of the request'
If you mark this snippet and "print it" or "inspect it", you will see a prompt dialog and can type something into it. When you accept the dialog with OK or return, you will get the entered String back as the return value of request:.
Getting ten numbers could be done like this:
(1 to: 10) collect: [:each | (UIManager default request: 'Enter number ', each asString) asNumber ]
The result will be an Array of the entered numbers.
Or, without using collect: and building up the collection yourself:
numbers := OrderedCollection new.
10 timesRepeat:
[ numbers add: (UIManager default request: 'Enter next number') asNumber ].
numbers do: [:each | Transcript show: each ].
You might also like UIManager default chooseFrom:. Browse the UIManager class and try out the various methods.
Note that Pharo's playground (called workspace in most other Smalltalks) already does what a REPL does, albeit it is not limited to line-based input. You can type Smalltalk expressions, evaluate them and have the results printed there. I am aware that this information does not give you the experience of porting your calculator app from C++. But I guess the way how the I/O works, or rather the interaction with the user, is not the essence of the programs you are trying to port, right? So you might as well write a class Calculator, in which you implement your calculator app, taking a String as input and returning the resulting number, and then invoke it from the playground by evaluating an expression like the following:
Calculator new calculate: '3 + 4'
If you really, really want to stick to console stuff and miss the benefits of the usual Smalltalk IDE and the experience of learning and using it, you might be better off with GNU Smalltalk. I think there are ways to create console applications with Pharo as well, but I would not recommend that to Smalltalk newcomers and I will leave that answer to someone who has already done it once.
You can use Pharo and get immediate feedback from the terminal like this:
➜ ./pharo Pharo.image eval "6+5"
11
Whatever you have between these quotes is being used as source by the compiler and the answered object will be printed to the stdout. In that example, it will be using SmallInteger>>asString behind the scenes.
For making a REPL, you don't need a lot. If you want to take a look, I've made REPLEndpoint using the Zinc HTTP server. In REPLEndpoint >> post you'll find the part where it uses the snippet you send to be evaluated:
snippet := '6+5'.
answer := OpalCompiler new evaluate: snippet.
answer
And answer will be the 11 SmallInteger instance you'd expect.
For additional hints on how your command line based REPL, take a look at the EvaluateCommandLineHandler class as it implements the basic step of what a REPL would do.

Python: Grab text printed to console

I'm using a complicated python module called CAMFR. In one function, it calculates a value that I want to use (to plot or otherwise), but unfortunately the module prints this value to the python console but doesn't return it as a variable!
(I have poked through the source code to see if I can recompile the module to return the values, but this looks excessively difficult at my programming level, considering it's written in C++ and uses Boost etc. I just don't get it unfortunately.)
SO, option number two is to grab the text printed to the console and parse out the value I need.
How can I intercept or otherwise acquire this function's console output text in Python (2.7)? (I will RegEx it afterwards.)
Thanks!
Here is an example of the text printed to the Python console:
<<a lot of other output, and then at the end of the function:>>
...
# 1.05554 4.65843e-05 5.54592 0.0903205 1
# 1.05554 2.87907e-05 3.42757 0.0903205 1
# 1.05554 2.87907e-05 3.42757 0.0903205 1
Done pass 1: lambda 1.05554, gain 3.42757
I ultimately want to grab the Lambda=1.05544 & Gain=3.42757 values, for example, and shove them into variables. Grabbing the entire console output of this one function would allow me to do that via a subsequent RegEx search, so I'm looking for a way to do that.
I apologize if there is another thread with the answer I need, I could not figure out google search terms that got me what I needed. Thanks for your patience & generous help!

Adding a script in a C++ application

I'm working on a project simulating a stock market. People buy and sell a stock and I would like to call each turn a script to try a strategy against the market.
What I want is a function in C++ which send an vector of integer as argument to a vba or python script which return an array of 3 integers.
I've searched for a solution but all i could find is a way to execute a script in python, but I don't know how I can send and get an argument from this script.
I think my problem is common but i don't know where to head to find a solution.
Thank you!
(I'm not a native english speaker so sorry if I made grammar error)
On windows you use the function CreateProcess() to start another program. Use the full path of the python interpreter as the first argument. Start the second argument with the path to the python script.
If you can fit a string representing your vector in 32768 characters, you can supply the vector in the second argument to CreateProcess.
A more flexible option is create a child process with redirected in- and output, as shown here. You can then write the vector to the standard input of the python process and read the answer back from its standard output.
There are many ways to do this.
The way I would do it is to popen() your "script" [which would be something like "python myscript.py -arg1 -arg2"]. Depending on how large your vector is, you could either store it in a file or pass it as part of the arguments [there is a limit in Windows of something like 8KB for the argument string].
The output would then appear as the result from popen()'s pipe.
Use Boost.Python. It will help you to embed python in your app.

Is there a search engine for C++ commands?

I do C++ and R programming since last 3 years.
I wish to know is there a search engine for C++ commands where I can find all the details regarding the command.
This is the example of what I am looking for:
This is a search engine for R commands:
http://www.rseek.org/
Google works pretty well.
If you only want C++ hits, use the site: restriction, as in "site:cppreference.com emplace_back"
Perhaps "site:cppreference.com pow" is a better example, since pow by itself would normally come up with many unrelated hits.
Of course, keyword search works also, try "site:cppreference.com natural logarithm"
I use this often: http://www.cplusplus.com/. It has a search box.

Easy ways to try out and test Lisp syntax?

Clojure has introduced me to the concept of Lisp syntax, and I'm interested, but it's a pain to get the Clojure repl set up and use it on different machines. What other resources are there out there for actually on-the-fly testing and playing with Lisp syntax?
I'm imagining something like a website where you can input rudimentary code, or a browser add-on, or even just a standalone application that steps you through Lisp (something that runs on Linux/Ubuntu).
Haven't been able to find anything like that to start me off in a simple/accessible way.
The SISC Online REPL is exactly what you need. It accepts Scheme syntax, which is a variant of Lisp.
For a standalone app I like PLT Scheme because it seems to work the same on every platform I've tried. I was previously using MIT Scheme on Ubuntu, but decided to switch when I bought a new machine with 64-bit Vista installed.
At the risk of losing all of my rep points, try newlisp.
I've used LispBox in the past. Easy to set up and get going, but I have to admit that Emacs is second nature to me. If you're unfamiliar with that, you may can use another editor, but getting intimate with Emacs will help you live comfortably in Lispville.
It's not hard to get to a Clojure REPL nowadays.
Go to http://build.clojure.org/ and download clojure.jar.
Install a JVM.
java -jar clojure.jar
This should work on any machine that has a JVM installed.
For more fun, install rlwrap and use rlwrap java -jar clojure.
For learning Lisp the LispWorks personal edition is fine: LispWorks downloads. There are versions for Mac OS X, Windows, Linux and FreeBSD. All have the same user interface capabilities and this includes an editor and listener - plus lots of other tools. On Linux and FreeBSD in currently (LispWorks 5) uses X11/Motif for the GUI - this will change in a future version (LispWorks 6) to GTK. So to run it now under Linux, you need to have the Motif lib installed. Other than that using it is relatively painless. There are some restrictions to it (only 5 hours runtime, then you need to save and restart, ...) and the full version is commercial. But for learning some Lisp basics, it is quite good.
Franz has an online REPL for Allegro Common Lisp.
http://www.franz.com/products/allegrocl/prompt/
codepad.org is a nice simple online way to enter and run code (in many different languages, including Scheme). I use it all the time for testing out snippets of code to use in SO answers.
I won't edit Lisp code without an editor that does what Emacs will do with the following configuration:
(define-key lisp-mode-shared-map "[" 'insert-parentheses)
(define-key lisp-mode-shared-map "]" 'move-past-close-and-reindent)
The former inserts balanced parentheses. If you give it a numeric prefix argument, it inserts that many nested pairs. By default, it inserts one. If you have a text region marked, it encloses that region in the innermost inserted pair. That means that you'll never open a parenthesis that's not closed.
The latter is harder to explain, as it's used less frequently. It's more of a navigation command than an insertion command. It confirms that you're done editing the current form and moves the cursor up, out, and past it, preparing for the next likely insertion.
With these keys bound, one no longer needs to use the Shift key to access the parentheses. Also, this leaves the parentheses keys bound as normal, for when sexp repair or a literal parenthesis character is required. I stole the bracket keys because they're used so infrequently in Emacs Lisp and Common Lisp. The bracket characters are still accessible with meta key bindings:
(defmacro make-key-inserter (def)
"Substitute for `self-insert-command'."
`(lambda (arg)
(interactive "*P")
(insert-char ,def (prefix-numeric-value arg))))
(define-key lisp-mode-shared-map "\M-[" (make-key-inserter ?\[))
(define-key lisp-mode-shared-map "\M-]" (make-key-inserter ?\]))
It's not essential to use Emacs, but don't settle for less with another editor that can't at least match this capability. There's also a whole family of commands for navigating and manipulating the sexp tree as a tree. Understanding why that's valuable will require you to fumble around for a while until you stop seeing syntax and start seeing the tree.
Since you're using Ubuntu, I'd just install some of the packages and give them a try.
Common Lisp: apt-get install clisp
Scheme: apt-get install drscheme
These aren't the only packaged implementations, but maybe the easier to get started with. You'll be able to play at a REPL and also run your own scripts through the interpreter.
BioBike provides a full Common Lisp evaluator through the web (with extras like a knowledge representation system, biocomputing, and an alternative visual langauge as well).
If you just want to play with LISP, interactively, quickly, GNU Emacs has a LISP interpreter built in, and listening in the *scratch* buffer. Type an S-expression, position immediately after it, and then hit Ctrl-J to evaluate it. Or <ESC>: will put an Eval: prompt in the minibuffer, accept an S-expression, and evaluate it.
You can define functions, using defun, and test things that way. You have access to ALL of the GNU Emacs built-in functions, and anything you have loaded. If you want to keep things around, you can put them in your .emacs file.
https://github.com/fogus/himera
was very easy for me to setup on a https://www.nitrous.io virtual box. Makes a nice web interface.
Downloading and running clojure-1.6.0.jar on my windows (XP) box was as easy as using this script to run the REPL :
java -cp clojure-1.6.0.jar clojure.main