1 people like it.

Seattle F# Meetup 7/17/2013 Example Code - Imperative

Imperative-style examples used during my talk for the Seattle F# Meetup on 7/17/2013. See corresponding functional-style examples at http://fssnip.net/iP

  1: 
  2: 
  3: 
  4: 
  5: 
  6: 
  7: 
  8: 
  9: 
 10: 
 11: 
 12: 
 13: 
 14: 
 15: 
 16: 
 17: 
 18: 
 19: 
 20: 
 21: 
 22: 
 23: 
 24: 
 25: 
 26: 
 27: 
 28: 
 29: 
 30: 
 31: 
 32: 
 33: 
 34: 
 35: 
 36: 
 37: 
 38: 
 39: 
 40: 
 41: 
 42: 
 43: 
 44: 
 45: 
 46: 
 47: 
 48: 
 49: 
 50: 
 51: 
 52: 
 53: 
 54: 
 55: 
 56: 
 57: 
 58: 
 59: 
 60: 
 61: 
 62: 
 63: 
 64: 
 65: 
 66: 
 67: 
 68: 
 69: 
 70: 
 71: 
 72: 
 73: 
 74: 
 75: 
 76: 
 77: 
 78: 
 79: 
 80: 
 81: 
 82: 
 83: 
 84: 
 85: 
 86: 
 87: 
 88: 
 89: 
 90: 
 91: 
 92: 
 93: 
 94: 
 95: 
 96: 
 97: 
 98: 
 99: 
100: 
101: 
102: 
103: 
104: 
105: 
106: 
107: 
108: 
109: 
110: 
111: 
112: 
113: 
114: 
115: 
116: 
117: 
118: 
119: 
120: 
121: 
122: 
123: 
124: 
125: 
126: 
127: 
128: 
129: 
130: 
131: 
132: 
133: 
134: 
135: 
136: 
137: 
138: 
139: 
140: 
141: 
142: 
143: 
144: 
145: 
146: 
147: 
148: 
149: 
150: 
151: 
152: 
153: 
154: 
155: 
156: 
157: 
158: 
159: 
160: 
161: 
162: 
163: 
164: 
165: 
166: 
namespace Talk

open System
open System.Threading

(* PATTERN MATCHING *)

module Example1 =
    let mutable message = null
    let key = Console.ReadKey().KeyChar

    if key = 'Q' then
        message <- "Quit!"
    elif key = '?' then
        message <- "Help!"
    else
        message <- sprintf "You hit %c" key

    printfn "%s" message


module Example2 =
    let processArray (arr : int array) = 
        let mutable result = null

        if arr <> null then
            if arr.Length = 1 && arr.[0] = 42 then
                result <- "1 element, 42"
            elif arr.Length = 3 then
                let x = arr.[0]
                let y = arr.[1]
                if x < y then
                    result <- sprintf "%d < %d" x y
                else
                    let z = arr.[2]
                    result <- sprintf "3 elements, last is %d" z
        if result = null then
            result <- sprintf "%A" arr

        result


(* ACTIVE PATTERNS *)

module Example3 =
    let describeNumber n =
        match n with
        // 0, 1, and negatives are not considered prime or composite
        | 0
        | 1
        | _ when n < 0 ->
            printfn "n is neither prime nor composite"
        // process positive numbers
        | _ ->
            let mutable factors = []
            let mutable remaining = n
            let mutable divisor = 2

            // build up list of factors
            while remaining > 1 do
                if remaining % divisor = 0 then
                    factors <- divisor :: factors
                    remaining <- remaining / divisor
                else
                    divisor <- divisor + 1

            // if only 1 factor, it's prime.  otherwise, composite
            match factors.Length with
            | 1 -> printfn "n is prime"
            | _ -> printfn "n in composite, with factors %A" factors


(* RECURSIVE LOOPS *)

module Example4 =
    (**** these work ok, but can be implemented with recursion ****)

    // 'for' loops
    for i = 1 to 5 do
        printfn "%d" i

    for i in 10 .. -2 .. 1 do
        printfn "%d" i
    
    // 'foreach' loop
    for i in [1; 3; 5; 9] do
        printfn "%d" i

    // 'while' loop, no break
    let start = DateTime.Now
    while (DateTime.Now - start) < TimeSpan.FromSeconds(2.) do
        printfn "Looping..."
        Thread.Sleep(300)


module Example5 =
    (*** these are more awkward ***)

    // 'while' loop with break
    let rnd = Random()
    let start = DateTime.Now
    let mutable keepLooping = true
    while keepLooping && ((DateTime.Now - start) < TimeSpan.FromSeconds(2.)) do
        printfn "Looping..."
        Thread.Sleep(300)
        if rnd.Next() % 10 = 0 then
            keepLooping <- false  // no 'break' keyword


    // 'for' loop with non-constant increment
    //     not possible with built-in 'for' loops


module Example6 = 

    let factorPositive n =         
         let mutable remaining = n
         let mutable factors = []
         let mutable divisor = 2

         // build up list of factors
         while remaining > 1 do
             if remaining % divisor = 0 then
                 factors <- divisor :: factors
                 remaining <- remaining / divisor
             else
                 divisor <- divisor + 1

         factors

(* HIGHER-ORDER FUNCTIONS FOR COLLECTION PROCESSING *)

module Example7 = 
    // map
    let myArray = [|"one"; "two"; "three"|]    
    let stringLengths : int array = 
        Array.zeroCreate myArray.Length
    for i = 0 to myArray.Length - 1 do
        stringLengths.[i] <- myArray.[i].Length


module Example8 = 
    // fold
    let myArray = [|"one"; "two"; "three"|]
    let mutable sumOfStringLengths = 0
    for s in myArray do
        sumOfStringLengths <- sumOfStringLengths + s.Length


module Example9 = 
    // filter
    let myArray = [|"one"; "two"; "three"|]
    let filtered =
        let temp = ResizeArray<string>()
        for s in myArray do
            if s.Length = 3 then
                temp.Add(s)
        temp.ToArray()
        
module Example10 =
    // iter
    let myArray = [|"one"; "two"; "three"|]
    for s in myArray do
        let length = s.Length
        if length = 3 then
            printfn "Length of %A is %d" s length
namespace System
namespace System.Threading
val mutable message : string

Full name: Talk.Example1.message
val key : char

Full name: Talk.Example1.key
type Console =
  static member BackgroundColor : ConsoleColor with get, set
  static member Beep : unit -> unit + 1 overload
  static member BufferHeight : int with get, set
  static member BufferWidth : int with get, set
  static member CapsLock : bool
  static member Clear : unit -> unit
  static member CursorLeft : int with get, set
  static member CursorSize : int with get, set
  static member CursorTop : int with get, set
  static member CursorVisible : bool with get, set
  ...

Full name: System.Console
Console.ReadKey() : ConsoleKeyInfo
Console.ReadKey(intercept: bool) : ConsoleKeyInfo
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val processArray : arr:int array -> string

Full name: Talk.Example2.processArray
val arr : int array
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
type 'T array = 'T []

Full name: Microsoft.FSharp.Core.array<_>
val mutable result : string
property Array.Length: int
val x : int
val y : int
val z : int
val describeNumber : n:int -> unit

Full name: Talk.Example3.describeNumber
val n : int
val mutable factors : int list
val mutable remaining : int
val mutable divisor : int
property List.Length: int
val i : int
val start : DateTime

Full name: Talk.Example4.start
Multiple items
type DateTime =
  struct
    new : ticks:int64 -> DateTime + 10 overloads
    member Add : value:TimeSpan -> DateTime
    member AddDays : value:float -> DateTime
    member AddHours : value:float -> DateTime
    member AddMilliseconds : value:float -> DateTime
    member AddMinutes : value:float -> DateTime
    member AddMonths : months:int -> DateTime
    member AddSeconds : value:float -> DateTime
    member AddTicks : value:int64 -> DateTime
    member AddYears : value:int -> DateTime
    ...
  end

Full name: System.DateTime

--------------------
DateTime()
   (+0 other overloads)
DateTime(ticks: int64) : unit
   (+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: DateTimeKind) : unit
   (+0 other overloads)
property DateTime.Now: DateTime
Multiple items
type TimeSpan =
  struct
    new : ticks:int64 -> TimeSpan + 3 overloads
    member Add : ts:TimeSpan -> TimeSpan
    member CompareTo : value:obj -> int + 1 overload
    member Days : int
    member Duration : unit -> TimeSpan
    member Equals : value:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member Hours : int
    member Milliseconds : int
    member Minutes : int
    ...
  end

Full name: System.TimeSpan

--------------------
TimeSpan()
TimeSpan(ticks: int64) : unit
TimeSpan(hours: int, minutes: int, seconds: int) : unit
TimeSpan(days: int, hours: int, minutes: int, seconds: int) : unit
TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : unit
TimeSpan.FromSeconds(value: float) : TimeSpan
Multiple items
type Thread =
  inherit CriticalFinalizerObject
  new : start:ThreadStart -> Thread + 3 overloads
  member Abort : unit -> unit + 1 overload
  member ApartmentState : ApartmentState with get, set
  member CurrentCulture : CultureInfo with get, set
  member CurrentUICulture : CultureInfo with get, set
  member DisableComObjectEagerCleanup : unit -> unit
  member ExecutionContext : ExecutionContext
  member GetApartmentState : unit -> ApartmentState
  member GetCompressedStack : unit -> CompressedStack
  member GetHashCode : unit -> int
  ...

Full name: System.Threading.Thread

--------------------
Thread(start: ThreadStart) : unit
Thread(start: ParameterizedThreadStart) : unit
Thread(start: ThreadStart, maxStackSize: int) : unit
Thread(start: ParameterizedThreadStart, maxStackSize: int) : unit
Thread.Sleep(timeout: TimeSpan) : unit
Thread.Sleep(millisecondsTimeout: int) : unit
val rnd : Random

Full name: Talk.Example5.rnd
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
Random() : unit
Random(Seed: int) : unit
val start : DateTime

Full name: Talk.Example5.start
val mutable keepLooping : bool

Full name: Talk.Example5.keepLooping
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
val factorPositive : n:int -> int list

Full name: Talk.Example6.factorPositive
val myArray : string []

Full name: Talk.Example7.myArray
val stringLengths : int array

Full name: Talk.Example7.stringLengths
type Array =
  member Clone : unit -> obj
  member CopyTo : array:Array * index:int -> unit + 1 overload
  member GetEnumerator : unit -> IEnumerator
  member GetLength : dimension:int -> int
  member GetLongLength : dimension:int -> int64
  member GetLowerBound : dimension:int -> int
  member GetUpperBound : dimension:int -> int
  member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads
  member Initialize : unit -> unit
  member IsFixedSize : bool
  ...

Full name: System.Array
val zeroCreate : count:int -> 'T []

Full name: Microsoft.FSharp.Collections.Array.zeroCreate
val myArray : string []

Full name: Talk.Example8.myArray
val mutable sumOfStringLengths : int

Full name: Talk.Example8.sumOfStringLengths
val s : string
property String.Length: int
val myArray : string []

Full name: Talk.Example9.myArray
val filtered : string []

Full name: Talk.Example9.filtered
val temp : Collections.Generic.List<string>
type ResizeArray<'T> = Collections.Generic.List<'T>

Full name: Microsoft.FSharp.Collections.ResizeArray<_>
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
Collections.Generic.List.Add(item: string) : unit
Collections.Generic.List.ToArray() : string []
module Example10

from Talk
val myArray : string []

Full name: Talk.Example10.myArray
val length : int

More information

Link:http://fssnip.net/iO
Posted:7 years ago
Author:Lincoln Atkinson
Tags: talk , imperative , meetup , examples