# Functionel Programming - Assignments ###### tags: `F#` ## Assignment 01 ```F# module Programfs open System // exericse 1.1 let sqr x = x * x;; // exercise 1.2 let pow x n = System.Math.Pow(x,n);; // ikke komma... // exercise 1.3 let rec sum = function |0 -> 1 |n -> n + sum(n-1);; // exercise 1.4 let rec fib = function |0 -> 0 |1 -> 1 |n -> fib(n-1) + fib(n-2);; // if-then-else // exercise 1.5 let rec fact= function |0 -> 1 |n -> n * fact(n-1) let rec power = function |(x,0) -> 1.0 |(x,n) -> x * power(x, n-1) //1.5A // Type: float * int // 1.5B // Type: int // 1.5C // Type: float // 1.5D // Type: (float * int -> float) * (int -> int) // Exercise 1.6 let dup (s:string) = s + s // Exercise 1.7 let rec dupn (s : string) = function |0 -> "" |x -> s ^ dupn s (x-1) // Exercise 1.8 let rec bin = function |(n,0) -> 1 |(n,k) when k=n -> 1 |(n,k) -> bin (n-1, k-1) + bin(n-1, k) // match statement... // Exercise 1.9 let rec f = function |(0,y) -> y |(x,y) -> f(x-1, x*y) // 1) type of f: int * int -> int // 2) when x = 0 // 3) // a) (* * f(2,3): The arguement matches the pattern (n, k) in the first clause giving the binding n |-> 2 and k |-> 3 bindings: f(x,y) ~> (f(m,n), [m |-> x, n |-> y]) f(2,3) ~> f(x-1, x*y), [m |-> 2, n |-> 3] ~> f(2-1, 2*3) ~> f(1, 6) * *) //4 // if a_1 and a_2 are values of type T1 and T2 then (a_1,a_2) is a value of type T1*T2 // Exercise 1.10 let test(c,e) = if c then e else 0 // a) bool * int -> int // b) (* test(false, fact(-1)) ~> test(0) ---> 0 *) // c) // infinte evaluation because applying fact to a negative //integer leads to an inifinite evaluation. // Exercise 1.11 // curry: let curry f = fun a -> fun b -> f (a,b);; // uncurry: let uncurry g = fun (a,b) -> g a b // Exercise 1.12 let empty (letter: char, pointValue: int) = fun (pos: int) -> (letter, pointValue) // Exercise 1.13 let add newPos (letter: char, pointValue: int) word pos = if newPos = pos then (letter, pointValue) else word pos // Exercise 1.14 let hello = empty('H',4) |> add 1 ('E',1) |> add 2 ('L',1) |> add 3 ('L',1) |> add 4 ('O',1) // Exercise 1.15 let singleLetterScore word pos = match word(pos) with |(_,pointValue) -> pointValue let doubleLetterScore word pos = match word(pos) with |(_,pointValue) -> pointValue * 2 let trippleLetterScore word pos = match word(pos) with |(_,pointValue) -> pointValue ``` ## Assignment 02 ```F# ```