Interactive programming (repl): Difference between revisions

From Rosetta Code
Content added Content deleted
(add language: Retro)
(Pari/GP)
Line 249: Line 249:
and again press C-. C-l to execute the code.
and again press C-. C-l to execute the code.
You will see the result in the "*Oz Emulator*" buffer.
You will see the result in the "*Oz Emulator*" buffer.

=={{header|PARI/GP}}==
GP *is* a REPL built on the Pari library. You can start it from the command line with <code>gp</code>, though you may wish to change to your Pari directory first so it can read your <code>.gprc</code> file. Alternatively, if you are using a GUI, double-click the shortcut.

<lang>f(s1,s2,sep)=Str(s1, sep, sep, s2);</lang>


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 16:38, 2 November 2010

Task
Interactive programming (repl)
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

Works with: SAM 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))

  1. '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) > }

  1. value: <f>

? f("Rosetta", "Code", ":")

  1. 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 "\".

Erlang

<lang erlang>$erl 1> F = fun(X,Y,Z) -> string:concat(string:concat(X,Z),string:concat(Z,Y)) end.

  1. Fun<erl_eval.18.105910772>

2> F("Rosetta", "Code", ":"). "Rosetta::Code" </lang>

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

Works with: GNU 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>

HicEst

Start HicEst e.g. with:
"c:\Program Files\HicEst\HicEst.exe E:\Rosetta\Interactive_programming.hic f('Rosetta', 'Code', ':')"
Type the following script. Each line is executed (and incrementally compiled) when it is typed: <lang HicEst>CHARACTER A*40, B*40, C*40

READ(Text=$CMD_LINE, Format=",,,") A, B, C WRITE(ClipBoard, Name) A, B, C  ! A=Rosetta; B=Code; C=:;

WRITE(ClipBoard) TRIM(A) // ':' // TRIM(C) // TRIM(B)  ! Rosetta::Code</lang>

J

J runs in command mode by default. Starting J depends on your operating system and other factors, but typically would involve double clicking on an icon, or starting one of several programs from a command line (j, jwd, jconsole, jee, jhs -- though note that jhs would also require a web browser and visiting a localhost url).

This is a session log once the os specific stuff has been handled: <lang j> f=: [: ; 0 2 2 1&{

  f 'Rosetta';'Code';':'

Rosetta::Code</lang>

JavaScript

Works with: Rhino

<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>

Works with: UCB 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
  1. let f s1 s2 sep = String.concat sep [s1; ""; s2];;

val f : string -> string -> string -> string = <fun>

  1. f "Rosetta" "Code" ":";;

- : string = "Rosetta::Code"

  1. </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.

PARI/GP

GP *is* a REPL built on the Pari library. You can start it from the command line with gp, though you may wish to change to your Pari directory first so it can read your .gprc file. Alternatively, if you are using a GUI, double-click the shortcut.

<lang>f(s1,s2,sep)=Str(s1, sep, sep, s2);</lang>

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

  1. 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>

Perl 6

Using Rakudo. <lang perl6>$ rakudo/perl6 > sub f($str1,$str2,$sep) { $str1~$sep x 2~$str2 }; f > f("Rosetta","Code",":"); Rosetta::Code > </lang>

PicoLisp

<lang bash>$ ./dbg</lang> <lang PicoLisp>: (de f (Str1 Str2 Sep)

  (pack Str1 Sep Sep Str2) )

-> f

(f "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>


Prolog

Works with SWI-Prolog.
Prolog works in its own environnment.
Start the interpreter by typing pl at the command line (or by clicking on the exe). <lang Prolog>% library(win_menu) compiled into win_menu 0.00 sec, 12,872 bytes % library(swi_hooks) compiled into pce_swi_hooks 0.00 sec, 2,404 bytes % The graphical front-end will be used for subsequent tracing % c:/users/joel-seven/appdata/roaming/swi-prolog/pl.ini compiled 0.13 sec, 876,172 bytes XPCE 6.6.66, July 2009 for Win32: NT,2000,XP Copyright (C) 1993-2009 University of Amsterdam. XPCE comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. The host-language is SWI-Prolog version 5.10.0

For HELP on prolog, please type help. or apropos(topic).

        on xpce, please type manpce.

1 ?- assert((f(A, B,C) :- format('~w~w~w~w~n', [A, C, C, B]))). true.

2 ?- f('Rosetta', 'Code', ':'). Rosetta::Code true.

3 ?- </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>

Retro

Retro's interpreter is started automatically. Once you see the "ok" prompt, you can proceed to enter code:

<lang Retro>: f ( $$$-$ ) &prepend sip prepend append tempString ; "Rosetta" "Code" ":" f</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>

Scala

Scala has a REPL -- Read, Evaluate & Print Loop. Being a compiled language, everything you type is encapsulated into a compilable template, compiled, executed, and the return value assigned to a special variable and displayed.

One invokes the REPL by just typing "scala", which is either a shell script or a batch file depending on one's operating system:

<lang scala>C:\>scala Welcome to Scala version 2.8.0.r21356-b20100407020120 (Java HotSpot(TM) Client V M, Java 1.6.0_05). Type in expressions to have them evaluated. Type :help for more information.

scala> "rosetta" res0: java.lang.String = rosetta</lang> Scala's REPL, starting with version 2.8, offers both auto-completion and alternatives when typing TAB. For instance, to check what methods are available on a String, one may do the following: <lang scala>scala> "rosetta".

!= ## $asInstanceOf $isInstanceOf + == charAt clone codePointAt codePointBefore codePointCount compareTo compareToIgnoreCase concat contains contentEquals endsWith eq equals equalsIgnoreCase finalize getBytes getChars getClass hashCode indexOf intern isEmpty lastIndexOf length matches ne notify notifyAll offsetByCodePoints regionMatches replace replaceAll replaceFirst split startsWith subSequence substring synchronized this toCharArray toLowerCase toString toUpperCase trim wait

scala> "rosetta".+(":") res1: java.lang.String = rosetta:</lang> One can use `object`, `class`, `trait`, `case object`, `case class`, `def`, `val` and `var` definitions at any point. However, `package` and `package object` definitions are not allowed. <lang scala>scala> val str1 = "rosetta" str1: java.lang.String = rosetta</lang> Using these features, one can build the code for a method by testing it part of it individually: <lang scala>scala> val str2 = "code" str2: java.lang.String = code

scala> val separator = ":" separator: java.lang.String = :

scala> str1 + separator + str2 res2: java.lang.String = rosetta:code</lang> If one makes a mistake, the REPL will print an error message, and display the point at which the mistake was made. <lang scala>scala> def (str1: String, str2: String, separator: String) = <console>:1: error: identifier expected but '(' found.

      def (str1: String, str2: String, separator: String) =
          ^</lang>

If a definition takes more than a line, the REPL will print an idented "|" sign, and wait for more input. If one wishes to abort a definition, just enter two consecutive empty lines. <lang scala>scala> def f(str1: String, str2: String, separator: String) =

    | str1 + separator + str2

f: (str1: String,str2: String,separator: String)java.lang.String

scala> f("rosetta", "code", ":") res3: java.lang.String = rosetta:code

scala> f("code", "rosetta", ", ") res4: java.lang.String = code, rosetta</lang> Also starting with version 2.8, a line starting with a dot will be interpreted as a method call on the last result produced. <lang scala>scala> .length res5: Int = 13

scala></lang> The results are actually displayed with a special function, which pretty prints some results, and avoid eagerly evaluating others, where that could cause problems (such as infinite collections). <lang scala>scala> Array(1, 2, 3, 4) res8: Array[Int] = Array(1, 2, 3, 4)

scala> println(res8) [I@383244</lang> There are many other features, such as the ability to add new jars to the class path, executing commands on the shell, retrieving the last exception thrown, etc.

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

Works with: GNU 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>

SNOBOL4

Works with: Macro Spitbol
>spitbol code
SPITBOL-386   Release 3.7(ver 1.30.20)   Serial xxxxx
...
Enter SPITBOL statements:
? define('f(a,b,s)'):(z);f f = a s s b:(return);z
Success
?= f('Rosetta','Code',':')
Rosetta::Code
Success
?end
>

Standard ML

Works with: SML/NJ

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>