Using pipes in F#

|> is the pipe operator

let convertInchesToMeters x =
    0.0254 * x

let convertMetersToMilliMeters x =
    x * 1000.0

let convertMetersToCentiMeters x =
    x * 100.0

let millimeters = 130.0 |> convertInchesToMeters |> convertMetersToMilliMeters
let centimeters = 130.0 |> convertInchesToMeters |> convertMetersToCentiMeters

printfn "%f" millimeters
printfn "%f" centimeters
Posted in F#

Classes, conditionals, and pattern matching in F#

shiftPoint using conditions

open System

type Direction =
    | up = 0
    | down = 1
    | left = 2
    | right = 3

type Point(x:int, y:int) = class
    let mutable _x = 0
    let mutable _y = 0

    do
        _x <- x
        _y <- y

    member x.X with get() = _x and set(value) = _x <- value
    member x.Y with get() = _y and set(value) = _y <- value
    override x.ToString() = sprintf "%i, %i" _x _y
end

let shiftPoint (point:Point) (direction:Direction) (unitsBy:int) =
    if direction = Direction.up then
        point.Y <- point.Y + unitsBy
    elif direction = Direction.down then
        point.Y <- point.Y - unitsBy
    elif direction = Direction.left then
        point.X <- point.X - unitsBy
    elif direction = Direction.right then
        point.X <- point.X + unitsBy

let p1 = new Point(1, 1)

shiftPoint p1 Direction.up 9
shiftPoint p1 Direction.down 9
shiftPoint p1 Direction.left 9
shiftPoint p1 Direction.right 9

Console.Write(p1)

shiftPoint using pattern matching

open System

type Direction =
    | up = 0
    | down = 1
    | left = 2
    | right = 3

type Point(x:int, y:int) = class
    let mutable _x = 0
    let mutable _y = 0

    do
        _x <- x
        _y <- y

    member x.X with get() = _x and set(value) = _x <- value
    member x.Y with get() = _y and set(value) = _y <- value
    override x.ToString() = sprintf "%i, %i" _x _y
end

let shiftPoint (point:Point) (direction:Direction) (unitsBy:int) =
    match direction with
    | Direction.up ->
        point.Y <- point.Y + unitsBy
    | Direction.down ->
        point.Y <- point.Y - unitsBy
    | Direction.left ->
        point.X <- point.X - unitsBy
    | Direction.right ->
        point.X <- point.X + unitsBy
    | _ -> ()

let p1 = new Point(1, 1)

shiftPoint p1 Direction.up 9
shiftPoint p1 Direction.down 9
shiftPoint p1 Direction.left 9
shiftPoint p1 Direction.right 9

Console.Write(p1)
Posted in F#

Array and mapping in F#

let files = ["question1.doc"; "question2.doc"; "question3.doc"; "question4.doc"]

let filenameWithoutExtension (x:string) =
    let index = x.IndexOf "."
    if(index = -1) then raise (System.Exception("Extension not found"))
    else x.Substring (0, x.IndexOf ".")

let getListOfFilesWithoutExtension listFiles =
    Seq.map(fun x -> filenameWithoutExtension x) listFiles

let listOfFilesWithoutExtension = getListOfFilesWithoutExtension (files :> seq<string>)

for file in listOfFilesWithoutExtension do
    printfn "%s" file
Posted in F#