Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Fun with F#

Liam McLennan
September 14, 2016

Fun with F#

Liam McLennan

September 14, 2016
Tweet

More Decks by Liam McLennan

Other Decks in Programming

Transcript

  1. 7

  2. 7+2

  3. When each piece of a program denotes a value (and

    nothing else) = the denotational semantic
  4. Consequences • Mutable values cannot be allowed • Objects no

    longer make sense • Dependency injection is redundant • ‘Change tracking’ and tools like EF that rely on it are problematic
  5. Reducing Accidental Complexity public static void Quicksort(int[] elements, int left,

    int right) { int i = left, j = right; int pivot = elements[(left + right) / 2]; while (i <= j) { while (elements[i] < pivot) { i++; } while (elements[j] > pivot) { j--; } if (i <= j) { int tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i++; j--; } } if (left < j) { Quicksort(elements, left, j); } if (i < right) { Quicksort(elements, i, right); } }
  6. F# Equivalent let rec quicksort = function | [] ->

    [] | x :: xs -> let smaller = List.filter ((>) x) xs let larger = List.filter ((<=) x) xs quicksort smaller @ [x] @ quicksort larger
  7. // C# static int Square(int x) { var squared =

    x * x; return squared; } // F# let square x = x * x Functions
  8. Immutable Values // C# var numbers = new List<int> {

    1,2,3 }; numbers.Add(4); // F# let numbers = [3;2;1] let moreNumbers = 4 :: numbers
  9. Data and Operations (C#) public class TwoNumbers { int fst;

    int snd; public TwoNumbers(int fst, int snd) { this.fst = fst; this.snd = snd; } public int Add() { return fst + snd; } }
  10. Data and Operations (F#) type TwoNumbers = int * int

    let add ((fst,snd):TwoNumbers) = fst + snd
  11. A function with 2 arguments let distance x y =

    x - y |> abs // val distance : x:int -> y:int -> int distance 5 2 // val it : int = 3
  12. 32f2 32#d2 32f2 8#d2 32#d2 32#d2 32f2 32g2 32f2 16.#d2

    32- 16f2 8#d2 16#g2 32#g2 32#g2 32#g2 16g2 16.#d2 32- 8#a2 32#a2 32#a2 16#a2 16f2 16g2 8#g2 16g2 16g2 32g2 Jakob’ s Tune Emulato r
  13. PCM is a digital representation of analogue audio Sample rate

    is the number of sampler per second Bit depth is the number of bits of information in each sample Encoding a Sound Wave -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 Samples Sine
  14. Discriminated Unions type Day = Sunday | Monday | Tuesday

    | Wednesday | Thursday | Friday | Saturday