Interactive programming (repl)
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Many language implementations come with a command line interpreter (a.k.a. shell or REPL).
Show how to start the interpreter, then, as a small example of its use, interactively create a function of two strings and a separator that returns the strings separated by two concatenated instances of the separator.
For example, f('Rosetta', 'Code', ':') should return 'Rosetta::Code'
Note: this task is not about creating your own interpreter.
BASIC
This was tested with SAM BASIC, but it should work with most Basic interpreters.
A Basic interpreter is in command mode by default. Enter the following in command mode: <lang qbasic>10 DEF FN f$(a$, b$, s$) = a$+s$+s$+b$ PRINT FN f$("Rosetta", "Code", ":")</lang>
Clojure
With clojure.jar on the Java classpath, the Clojure REPL is invoked with java clojure.main. <lang lisp> Clojure 1.1.0 user=> (defn f [s1 s2 sep] (str s1 sep sep s2))
- 'user/f
user=> (f "Rosetta" "Code" ":") "Rosetta::Code" user=> </lang>
Common Lisp
The details of interactive use vary widely between implementations; this example is from SBCL. *
is the prompt. By default, SBCL compiles (not interprets) all code, unless sb-ext:*evaluator-mode*
is changed.
<lang lisp>$ rlwrap sbcl
This is SBCL 1.0.25, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
...
- (defun f (string-1 string-2 separator)
(concatenate 'string string-1 separator separator string-2))
F
- (f "Rosetta" "Code" ":")
"Rosetta::Code"
- </lang>
E
<lang e>$ rune # from an OS shell. On Windows there is also a desktop shortcut.</lang>
"?
" and ">
" are prompts for input; "#
" marks output.
<lang e>? def f(string1 :String, string2 :String, separator :String) { > return separator.rjoin(string1, "", string2) > }
- value: <f>
? f("Rosetta", "Code", ":")
- value: "Rosetta::Code"</lang>
If you type a definitely incomplete expression, such as "def f() {
", then it gives an ">
" prompt and takes additional lines. If the expression is not necessarily incomplete, you can continue anyway by ending a line with "\
".
Factor
Factor comes with a graphical interpreter called the listener. The listener can also be run in a console with the following command :
./factor -run=listener
<lang factor>( scratchpad ) : cool-func ( w1 w2 sep -- res ) dup append glue ; ( scratchpad ) "Rosetta" "Code" ":" cool-func . "Rosetta::Code"</lang>
Forth
All Forth systems come with an interpreter. On embedded systems, the interpreter functions as a monitor or lightweight operating system. (User input is shown here in italics.) <lang forth>$ gforth Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc. Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license' Type `bye' to exit : f ( separator suffix prefix -- ) compiled
pad place 2swap 2dup pad +place pad +place pad +place compiled pad count ; ok
s" :" s" Code" s" Rosetta" f cr type Rosetta::Code ok</lang>
F#
The F# interpreter is called fsi. As F# accepts multi-line input it will not evaluate the input until you enter two semi-colons together. <lang fsharp>Microsoft F# Interactive, (c) Microsoft Corporation, All Rights Reserved F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727
Please send bug reports to fsbugs@microsoft.com For help type #help;;
> let f a b sep = String.concat sep [a; ""; b] ;;
val f : string -> string -> string -> string
> f "Rosetta" "Code" ":" ;; val it : string = "Rosetta::Code"</lang>
Groovy
The groovysh interpreter requires a command-line interpreter (terminal) environment in which to run. This example was run under the CMD command-line interpreter on Microsoft Windows XP. <lang groovy>C:\Apps\groovy>groovysh Groovy Shell (1.6.2, JVM: 1.6.0_13) Type 'help' or '\h' for help.
groovy:000> f = { a, b, sep -> a + sep + sep + b } ===> groovysh_evaluate$_run_closure1@5e8d7d groovy:000> println f('Rosetta','Code',':') Rosetta::Code ===> null groovy:000> exit
C:\Apps\groovy></lang>
Haskell
The details of interactive use vary widely between implementations. This example is from GHCi.
<lang haskell>$ ghci
___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.4.2, for Haskell 98.
/ /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help.
Loading package base-1.0 ... linking ... done. Prelude> let f as bs sep = as ++ sep ++ sep ++ bs Prelude> f "Rosetta" "Code" ":" "Rosetta::Code"</lang>
J
J runs in command mode by default. This is a session log: <lang j> f=: [: ; 0 2 2 1&{
f 'Rosetta';'Code';':'
Rosetta::Code</lang>
JavaScript
<lang javascript>$ java -cp js.jar org.mozilla.javascript.tools.shell.Main Rhino 1.7 release 2 2009 03 22 js> function f(a,b,s) {return a + s + s + b;} js> f('Rosetta', 'Code', ':') Rosetta::Code js> quit() $</lang>
Logo
<lang logo>$ logo Welcome to Berkeley Logo version 5.6 ? to f :prefix :suffix :separator > output (word :prefix :separator :separator :suffix) > end f defined ? show f "Rosetta "Code ": Rosetta::Code ?</lang>
Lua
<lang lua>$ lua Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio > function conc(a, b, c) >> return a..c..c..b >> end > print(conc("Rosetta", "Code", ":")) Rosetta::Code ></lang>
M4
Here is a terminal session with output lines marked by "==>": <lang M4>$ m4 define(`f',`$1`'$3`'$3`'$2') ==> f(`Rosetta',`Code',`:') ==>Rosetta::Code m4exit</lang>
OCaml
Because you can enter expressions that span multiple lines, you have to type the double semicolon (";;") at the end so that it knows you are done.
<lang ocaml>$ ocaml
Objective Caml version 3.11.1
- let f s1 s2 sep = String.concat sep [s1; ""; s2];;
val f : string -> string -> string -> string = <fun>
- f "Rosetta" "Code" ":";;
- : string = "Rosetta::Code"
- </lang>
Also most often OCaml users invoke the toplevel with rlwrap or ledit to gain readline capabilities:
<lang ocaml>$ rlwrap ocaml</lang>
Octave
<lang octave>$ octave GNU Octave, version 3.0.2 Copyright (C) 2008 John W. Eaton and others. This is free software; see the source code for copying conditions. There is ABSOLUTELY NO WARRANTY; not even for MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'.
Octave was configured for "i586-mandriva-linux-gnu".
Additional information about Octave is available at http://www.octave.org.
Please contribute if you find this software useful. For more information, visit http://www.octave.org/help-wanted.html
Report bugs to <bug@octave.org> (but first, please read http://www.octave.org/bugs.html to learn how to write a helpful report).
For information about changes from previous versions, type `news'.
octave:1> function concat(a,b,c) > disp(strcat(a,c,c,b)); > endfunction octave:2> concat("Rosetta","Code",":"); Rosetta::Code octave:3></lang>
Oz
Mozart supports this style of programming with its Emacs interface. Go to the "Oz" buffer and enter <lang oz>declare fun {F As Bs Sep} {Append As Sep|Sep|Bs} end</lang> Press C-. C-l to evaluate the line.
Now enter <lang oz>{System.showInfo {F "Rosetta" "Code" &:}}</lang> and again press C-. C-l to execute the code. You will see the result in the "*Oz Emulator*" buffer.
Perl
Perl doesn't have an interpreter, but there is an interactive debugger: <lang perl>$ perl -de1
Loading DB routines from perl5db.pl version 1.3 Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 1
DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2}
DB<2> p f('Rosetta', 'Code', ':')
Rosetta::Code
DB<3> q</lang>
Alternative way:
<lang perl>$ perl
- Write the script here and press Ctrl+D plus ENTER when finished (^D means Ctrl+D):
sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2}; print f('Rosetta', 'Code', ':'); ^D Rosetta::Code $</lang>
Another:
<lang perl>$ perl -lpe '$_=eval||$@' sub f { join => @_[0, 2, 2, 1] }
f qw/Rosetta Code :/ Rosetta::Code</lang>
Pike
<lang pike> $ pike Pike v7.8 release 352 running Hilfe v3.5 (Incremental Pike Frontend) > string f(string first, string second, string sep){ >> write(first + sep + sep + second + "\n"); >> } > f("Rosetta","Code",":"); Rosetta::Code (1) Result: 0 > </lang>
PowerShell
PowerShell itself is already a shell and therefore an interactive environment is the default. <lang powershell>Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS Home:\> function f ([string] $string1, [string] $string2, [string] $separator) { >> $string1 + $separator * 2 + $string2 >> } >> PS Home:\> f 'Rosetta' 'Code' ':' Rosetta::Code PS Home:\></lang>
Python
Start the interpreter by typing python at the command line (or select it from a menu). You get a response showing the version of the interpreter being run before giving an input prompt of three greater-than characters and a space:
<lang python>python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, , string2])
>>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>></lang>
R
<lang r>$ R
R version 2.7.2 (2008-08-25) Copyright (C) 2008 The R Foundation for Statistical Computing ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R.
> f <- function(a, b, s) paste(a, "", b, sep=s) > f("Rosetta", "Code", ":") [1] "Rosetta::Code" > q() Save workspace image? [y/n/c]: n</lang>
Ruby
Start the interpreter by typing irb at the command line. You will see an input prompt, which by default is name of this program(name of main object):line number:indent level>
:
<lang ruby>$ irb irb(main):001:0> def f(string1, string2, separator) irb(main):002:1> [string1, , string2].join(separator) irb(main):003:1> end => nil irb(main):004:0> f('Rosetta', 'Code', ':') => "Rosetta::Code" irb(main):005:0></lang>
Scheme
Several interpreters exist for Scheme. These are just some examples. <lang>> scheme Scheme Microcode Version 14.9 MIT Scheme running under FreeBSD Type `^C' (control-C) followed by `H' to obtain information about interrupts. Scheme saved on Monday June 17, 2002 at 10:03:44 PM
Release 7.7.1 Microcode 14.9 Runtime 15.1
1 ]=> (define (f string-1 string-2 separator)
(string-append string-1 separator separator string-2))
- Value
- f
1 ]=> (f "Rosetta" "Code" ":")
- Value 1
- "Rosetta::Code"
1 ]=> ^D End of input stream reached Happy Happy Joy Joy. ></lang> <lang>> scheme48 Welcome to Scheme 48 1.8 (made by root on Wed Sep 24 22:37:08 UTC 2008) Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees. Please report bugs to scheme-48-bugs@s48.org. Get more information at http://www.s48.org/. Type ,? (comma question-mark) for help. > (define (f string-1 string-2 separator)
(string-append string-1 separator separator string-2))
- no values returned
> (f "Rosetta" "Code" ":") "Rosetta::Code" > ^D Exit Scheme 48 (y/n)? ^D I'll only ask another 100 times. Exit Scheme 48 (y/n)? ^D I'll only ask another 99 times. Exit Scheme 48 (y/n)? y ></lang>
Slate
<lang slate>slate[1]> s@(String traits) rosettaWith: s2@(String traits) and: s3@(String traits) [s ; s3 ; s3 ; s2]. [rosettaWith:and:] slate[2]> 'Rosetta' rosettaWith: 'Code' and: ':'. 'Rosetta::Code'</lang>
Smalltalk
<lang smalltalk>$ gst GNU Smalltalk ready
st> |concat| st> concat := [ :a :b :c | (a,c,c,b) displayNl ]. a BlockClosure st> concat value: 'Rosetta' value: 'Code' value: ':'. Rosetta::Code 'Rosetta::Code' st></lang>
Standard ML
Because you can enter expressions that span multiple lines, you have to type the semicolon (";") at the end so that it knows you are done.
<lang sml>$ sml Standard ML of New Jersey v110.67 [built: Fri Jul 4 09:00:58 2008] - fun f (s1, s2, sep) = String.concatWith sep [s1, "", s2]; [autoloading] [library $SMLNJ-BASIS/basis.cm is stable] [autoloading done] val f = fn : string * string * string -> string - f ("Rosetta", "Code", ":"); val it = "Rosetta::Code" : string -</lang>
Tcl
<lang tcl>$ tclsh % proc f {s1 s2 sep} {
append result $s1 $sep $sep $s2
} % f Rosetta Code : Rosetta::Code % exit</lang> A simple alternative (one-liners are most convenient in an interactive shell): <lang tcl>$ tclsh % proc f {a b s} {join [list $a "" $b] $s} % f Rosetta Code : Rosetta::Code %</lang>
TI-89 BASIC
To switch to the interpreter ("home screen"), press the HOME key.
■ x & s & s & y → f(x,y,s) Done ■ f("Rosetta", "Code", ":") "Rosetta::Code"
Input is left-aligned, output is right-aligned. “→” is typed by pressing STO▸, and “&” by pressing ◆ ×. All whitespace is optional.
UNIX Shell
<lang bash>$ sh sh-3.2$ concat() { echo "$1$3$3$2"; } sh-3.2$ concat Rosetta Code : Rosetta::Code sh-3.2$</lang>
Vedit macro language
To enter command mode, type <Esc>c, or to open command mode window, type <Esc>w. Or if the command mode window is already open, just click on the window.
To define a macro in text register 100: <lang vedit>RS(100, "RS(10, @1) RS(10, @3, APPEND) RS(10, @3, APPEND) RS(10, @2, APPEND)")</lang>
To call the macro: <lang vedit>RS(1,"Rosetta") RS(2,"Code") RS(3,":") Call(100) Message(@10)</lang>
- Programming Tasks
- Basic language learning
- AWK/Omit
- AutoHotkey/Omit
- D/Omit
- C sharp/Omit
- C/Omit
- Fortran/Omit
- Pascal/Omit
- Objective-C/Omit
- BASIC
- Clojure
- Common Lisp
- E
- Factor
- Forth
- F Sharp
- Groovy
- Haskell
- J
- JavaScript
- Logo
- Lua
- M4
- OCaml
- Octave
- Oz
- Perl
- Pike
- PowerShell
- Python
- R
- Ruby
- Scheme
- Slate
- Smalltalk
- Standard ML
- Java/Omit
- C++/Omit
- Tcl
- TI-89 BASIC
- UNIX Shell
- Vedit macro language
- ALGOL 68/Omit