FUNCTIONAL PROGRAMMING IN OCAML Functional Programming in OCAML Name Institution Date
FUNCTIONAL PROGRAMMING IN OCAML2 1. IMPLEMENTING THE PRIME NUMBER FUNCTIONAL PROGRAM Printf.printf "Enter number: "; let value = read_int () in let is_prime x = let bound = int_of_float (ceil (sqrt (float_of_int x))) in let rec ip_aux x n = if n > bound then true else if (x mod n) == 0 then false else (ip_aux x (n + 1)) in (ip_aux x 2) in Printf.printf "%d is %s\n" value (if (is_prime value) then "prime" else "not prime") OR letis_primen = let n = abs n in let recis_not_divisord = d * d > n || (n mod d <> 0 && is_not_divisor (d+1)) in n <> 1 && is_not_divisor 2;; val is_prime : int -> bool = <fun> # not(is_prime 1);; - : bool = true
FUNCTIONAL PROGRAMMING IN OCAML3 # is_prime 7;; - : bool = true # not (is_prime 12);; - : bool = true 2. IMPLEMENTING FIBONACCI SEQUENCE FUNCTIONAL PROGRAM <pre> # let rec fib n = if n<2 then n else fib(n-1) + fib(n-2);; val fib : int -> int = <fun> </pre> For example: <pre> # fib 10;; - : int = 55 </pre> The function below can be built as tail recursive by collecting two subsequent Fibonacci numbers. <pre> # let rec fib ?(r=1) ?(k=0) = function
FUNCTIONAL PROGRAMMING IN OCAML4 | 0 -> k | 1 -> r | f -> fib ~r:(r+k) ~k:r (f-1);; val fib : ?r:int -> ?k:int -> int -> int = <fun> </pre> 3. Given the program: According to the OCaml program above using static or lexical scoping leads to the following result: A.Static Scoping a)The outermost x is edged to 2. b)The f is edge to x+y+z. Because x will be edged statically, it will amount to z (the value of x is unchangeable because no variable can be assigned in OCAML programming language. c)The inner z will be edged to 4. d)In the assessment of the function, destitute variables entailed in the code uses the defined variable funy. A such, the environment x will edge to 2. Therefore, 2 + 4 = 6.
End of preview
Want to access all the pages? Upload your documents or become a member.