Calico FSharp

From IPRE Wiki
Jump to: navigation, search

F# is similar to OCaml and ML. A nice introduction can be found in the online book The F# Survival Guide.

In the interpreted command box, end code with ;; to signal the end of expression. In a file, start with module MyModule.

Graphics.Init();;
let r = Myro.random();;

You can use modules Myro and Graphics directly in the interpreter:

Graphics.Init()
let win = new Graphics._Window("Hello")
let line = new Graphics.Line(new Graphics.Point(0, 0),
                             new Graphics.Point(100, 100))
line.draw(win);;

And if this were in a file:

module MyModule

Graphics.Init()
let win = new Graphics._Window("Hello")
let line = new Graphics.Line(new Graphics.Point(0, 0),
                             new Graphics.Point(100, 100))
line.draw(win)
module MyRobotDance

Graphics.Init()
Myro.init()
Myro.forward(1., 1.)
Myro.turnLeft(1., .3)

Factorial, recursively:

let rec factorial n =
    match n with
    | 0 -> 1
    | _ -> n * factorial (n - 1);;

That version will run out of stack space at some point. To keep from crashing the stack, put the recursion in the tail position:

let rec factorial n result =
    if n <= 1 then result
    else
        factorial (n - 1) (n * result);;

Both of these will overflow integer, however.

calico object

F# supports the Calico: calico object so that you can interact with other languages, and also with the latest ICalico widgets for notebooks in a web browser.

Commands

Directive Description
#help;; Displays information about available directives.
#I "/search/path";; Specifies an assembly search path in quotation marks.
#load "source/file.fs";; Reads a source file, compiles it, and runs it.
#quit Terminates an F# Interactive session.
#r "Myro.dll";; References an assembly.
#time "on";; By itself, #time toggles whether to display performance information.
#time "off";; When it is enabled, F# Interactive measures real time, CPU time, and garbage collection information for each section of code that is interpreted and executed.