How to recursively get scalar value from 2 lists? - recursion

The task is to get scalar value from 2 lists recursively. I wrote the code that I think should work, but I am having some type related problem
let rec scalar2 (a, b) = function
| ([], []) -> 0
| ([x : int], [y : int]) -> x * y
| (h1::t1, h2::t2) ->
let sc : int = scalar2 (t1,t2)
sc + (h1 * h2)
The error is that scalar2 (t1,t2) reqested to be int, but it is int list * int list -> int
How this problem could be solved?

When defining a function using the function keyword, you don't need to name your parameters (a and b here). Note that your function body doesn't refer to a or b at all. You want scalar2 to be a function, and the function expression on the right hand side results in a function, so just assign this function to scalar2 directly.
let rec scalar2 = function
| ([], []) -> 0
| ([x : int], [y : int]) -> x * y
| (h1::t1, h2::t2) ->
let sc : int = scalar2 (t1,t2)
sc + (h1 * h2)
Your mistake is likely caused by a confusion with the usual way of defining a function, which doesn't use the function keyword:
let rec scalar2 (a,b) =
match (a,b) with
| ([], []) -> 0
| ([x : int], [y : int]) -> x * y
| (h1::t1, h2::t2) ->
let sc : int = scalar2 (t1,t2)
sc + (h1 * h2)
This way you need a match expression which does use the parameters a and b.
Note that both of these definitions are incomplete, since you haven't said what should happen when only one of the lists is non-empty.
To explain the type error in the original code, consider how F# evaluates let sc : int = scalar2 (t1,t2). Your original definition says that scalar2 (a,b) = function ..., and the left-hand side of this equality has the same form as the expression scalar2 (t1,t2).
So the scalar2 (t1,t2) gets replaced with the function ... expression, after substituting t1 for a and t2 for b. This leaves let sc : int = function ... which of course doesn't type-check.

Related

Why is it giving me this error? This expression has type Z.t but an expression was expected of type int

EDITED: Alright, this is the complete error :
45 | | _ -> Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)
^^^^^^^^^^
Error: This expression has type Z.t but an expression was expected of type
int
And this is the code in question :
let rec s1 num =
match num with
| 0 -> Z.of_int(1)
| 1 -> Z.of_int(2)
| _ -> Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)
and
sum_s1 num =
let rec sum_s1_impl (num, k) =
if (num-2 < 1) || (k > num-2) then 0
else (s1 k) * (s1 (num-k-1)) + (sum_s1_impl (num, k+1))
in sum_s1_impl (num, 1);;
I don't know where is the problem/how can I fix it (some tips)
Thanks!!
EDIT#2 :
let rec s1 num =
match num with
| 0 -> Z.of_int(1)
| 1 -> Z.of_int(2)
| _ -> Z.of_int(3 * (s1 (num-1)) + (sum_s1 num))
and
sum_s1 num =
let rec sum_s1_impl (num, k) =
if (num-2 < 1) || (k > num-2) then 0
else (s1 k) * (s1 (num-k-1)) + (sum_s1_impl (num, k+1))
in sum_s1_impl (num, 1);;
Even with the use of Z.of_int(3 * (s1 (num-1)) + (sum_s1 num))
I stil get the same error
Generally speaking you need to carefully track which of your parameters are of type int (ordinary OCaml integer) and which are Z.t (big integer). You seem to treat them as if they're the same type, which doesn't work in a strongly typed language.
The first reported error is for this expression:
Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)
If I look at the code for s1 it shows that it expects an int parameter, since it matches the parameter against 0, 1, etc. Similarly, the code for sum_s1 expects an int parameter since it applies the built-in - operator to the parameter.
With these assumptions, the first problem in this expression is that Z.of_int returns a big integer (Z.t). You can't multiply a big integer using the built-in * operator.
But note that this subexpression looks wrong also:
Z.(s1 (num - 1))
Since the expression is prefixed with Z., the operators will come from the Z module. Hence the - is of type Z.t -> Z.t -> Z.t. But you're applying it to num and 1 which are ordinary OCaml ints.
You need to go through the expressions and figure out the type you want for each subpart. Generally you want to do everything using big integers, so you should convert using Z.of_int whenever you have a regular OCaml int. Most of the parameters and return values of your functions should (in my opinion) be big integers.
You are multiplying non int type Z.of_int 3 by an int (* operator).
Try to do your operations with ints, and then convert the end result to Z.of_int (your result)
EDIT : Also, you can use built-in zerith operators, ie :
val add : t -> t -> t
Addition.
Check https://www-apr.lip6.fr/~mine/enseignement/l3/2015-2016/doc-zarith/Z.html

How can I create a type in order to accommodate the return value of my Ocaml function?

I am trying to implement a lazy fibonacci generator in Ocaml as shown below:
(* fib's helper *)
let rec fibhlpr n = if n == 0 then 0 else if n == 1 then 1 else fibhlpr (n-1) + fibhlpr (n-2);;
(* lazy fib? *)
let rec fib n = ((fibhlpr n), fun() -> fib (n+1));;
I am trying to return the result of fibhlpr (an int) and a function to retrieve the next value, but am not sure how. I think I have to create a new type in order to accommodate the two items I am returning, but I don't know what type fun() -> fib (n+1) returns. When messing around with the code, I received an error which informed me that
fun() -> fib (n+1) has type: int * (unit ->'a).
I am rather new to Ocaml and functional programming in general, so I don't know what this means. I tried creating a new type as follows:
type t = int * (unit -> 'a);;
However, I received the error: "Unbound type parameter 'a".
At this point I am truly stuck: how can I returns the two items that I want (the result of fibhlpr n and a function which returns the next value in the sequence) without causing an error? Thank you for any help.
If you want to define a lazy sequence, you can use the built-in sequence type
constructor Seq.t
let rec gen_fib a b () = Seq.Cons(a, gen_fib b (a+b))
let fib () = gen_fib 0 1 ()
This implementation also has the advantage that computing the n-th term of the sequence is O(n) rather than O(2^n).
If you want to keep using an infinite lazy type, it is also possible. However, you cannot use the recursive type expression
type t = int * (unit -> t)
without the -rectypes flag. And using -rectypes is generally ill-advised for beginners because it reduces the ability of type inference to identify programming errors.
It is thus better to simply use a recursive type definition as suggested by #G4143
type 'a infinite_sequence = { x:'a; next: unit -> 'a infinite_sequence }
let rec gen_fib a b () =
{ x = a; next = gen_fib b (a+b) }
let fib = gen_fib 0 1 ()
The correct type is
type t = int * (unit -> t)
You do not need a polymorphic 'a, because fibonacci only ever yields ints.
However, when you call the next function, you need to get the next value, but also a way to get the one after it, and so on and so on. You could call the function multiple times, but then it means that the function has mutable state, the above signature doesn't require that.
Try:
type 'a t = int * (unit -> 'a);
Your whole problems stems from this function:
let rec fib n = ((fibhlpr n), fun() -> fib (n+1))
I don't think the type system can define fib when it returns itself.. You need to create a new type which can construct a function to return.
I quickly tried this and it works:
type func = Func of (unit ->(int * func))
let rec fib n =
let c = ref 0 in
let rec f () =
if !c < n
then
(
c := !c + 1;
((fibhlpr !c), (Func f))
)
else
failwith "Done"
in
f
Following octachron's lead.. Here's a solution using Seq's unfold function.
let rec fibhlpr n =
if n == 0
then
0
else if n == 1
then
1
else
fibhlpr (n-1) + fibhlpr (n-2)
type func = Func of (unit -> (int * int * func))
let rec fib n =
(n, (fibhlpr n), Func(fun() -> fib (n+1)))
let seq =
fun x ->
Seq.unfold
(
fun e ->
let (c, d, Func f) = e in
if c > x
then
None
else
(
Some((c, d), f())
)
) (fib 0)
let () =
Seq.iter
(fun (c, d) -> Printf.printf "%d: %d\n" c d; (flush stdout)) (seq 30)
You started right saying your fib function returns an integer and a function:
type t = int * (unit -> 'a);;
But as the compiler says the 'a is not bound to anything. Your function also isn't polymorphic so that is has to return a type variable. The function you return is the fib function for the next number. Which also returns an integer and a function:
type t = int * (unit -> int * (unit -> 'a));;
But that second function again is the fib function for the next number.
type t = int * (unit -> int * (unit -> int * (unit -> 'a)))
And so on to infinity. Your type definition is actually recursive. The function you return as second half has the same type as the overall return type. You might try to write this as:
# type t = int * (unit -> t);;
Error: The type abbreviation t is cyclic
Recursive types are not allowed in ocaml unless the -rectypes option is used, which has some other side effects you should read about before using it.
A different way to break the cycle is to insert a Constructor into the cyclic type by making it a variant type:
# type t = Pair of int * (unit -> t)
let rec fibhlpr n = if n == 0 then 0 else if n == 1 then 1 else fibhlpr (n-1) + fibhlpr (n-2)
let rec fib n = Pair ((fibhlpr n), fun() -> fib (n+1));;
type t = Pair of int * (unit -> t)
val fibhlpr : int -> int = <fun>
val fib : int -> t = <fun>
Encapsulating the type recursion into a record type also works and might be the more common solution. Something like:
type t = { value : int; next : unit -> t; }
I also think you are missing the point of the exercise. Unless I'm mistaken the point of making it a generator is so that the function can compute the next fibonacci number from the two previous numbers, which you remember, instead of computing it recursively over and over.

Unexpected output type

I am doing practice with F#. I am trying to create a simple program capable to find me out a couple of prime numbers that, summed together, equal a natural number input. It is the Goldbach conjecture. A single couple of primes will be enough. We will assume the input to be a even number.
I first created a function to check if a number is prime:
let rec isPrime (x: int) (i: int) :bool =
match x % i with
| _ when float i > sqrt (float x) -> true
| 0 -> false
| _ -> isPrime x (i + 1)
Then, I am trying to develop a function that (a) looks for prime numbers, (b) compare their sum with the input 'z' and (c) returns a tuple when it finds the two numbers. The function should not be correct yet, but I would get the reason behind this problem:
let rec sumPrime (z: int) (j: int) (k: int) :int * int =
match isPrime j, isPrime k with
| 0, 0 when j + k > z -> (0, 0)
| 0, 0 -> sumPrime (j + 1) (k + 1)
| _, 0 -> sumPrime j (k + 1)
| 0, _ -> sumPrime (j + 1) k
| _, _ -> if j + k < z then
sumPrime (j + 1) k
elif j + k = z then
(j, k)
The problem: even if I specified that the output should be a tuple :int * int the compiler protests, claiming that the expected output should be of type bool. When in trouble, I usually refer to F# for fun and profit, that i love, but this time I cannot find out the problem. Any suggestion is greatly appreciated.
Your code has three problems that I've spotted:
Your isPrime returns a bool (as you've specified), but your match expression in sumPrime is matching against integers (in F#, the Boolean value false is not the same as the integer value 0). Your match expression should look like:
match isPrime j, isPrime k with
| false, false when j + k > z -> (0, 0)
| false, false -> ...
| true, false -> ...
| false, true -> ...
| true, true -> ...
You have an if...elif expression in your true, true case, but there's no final else. By default, the final else of an if expression returns (), the unit type. So once you fix your first problem, you'll find that F# is complaining about a type mismatch between int * int and unit. You'll need to add an else condition to your final match case to say what to do if j + k > z.
You are repeatedly calling your sumPrime function, which takes three parameters, with just two parameters. That is perfectly legal in F#, since it's a curried language: calling sumPrime with two parameters produces the type int -> int * int: a function that takes a single int and returns a tuple of ints. But that's not what you're actually trying to do. Make sure you specify a value for z in all your recursive calls.
With those three changes, you should probably see your compiler errors go away.

F#: multiplication of polynomials

I found this exercise in "Functional Programming Using F#" (4.22.3):
Declare infix F# operators for addition and multiplication of
polynomials in the chosen representation.
f(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n
The polynomial is reprsented as a list of integer. For example the polynomial f(x) = x^3 + 2 is represented by the list [2; 0; 0; 1]. Now I need a function that takes two lists of integers and returns a list of integers:
// polymul: int list -> int list -> int list
let polymul p q =
???
The authors gave this hint along with the exercise:
The following recursion formula is useful when defining the
multiplication:
0 * Q(x) = 0
(a0+a1*x+...+an*x^n) * Q(x) =
a0 * Q(x) + x * [(a1+a2*x+...+an*x^(n-1)) * Q(x)]
I could not come up with a solution for this exercise. Can anyone help me?
I have a solution. I took the hint and converted it one-to-one into F#. And it worked magically:
// multiplicate a polynomial with a constant
// polymulconst: float -> float list -> float list
let rec polymulconst c = function
| [] -> []
| a::rest -> c*a::polymulconst c rest
// multiplying a polynomial by x
// polymulx: float list -> float list
let polymulx = function
| [] -> []
| lst -> 0.0::lst
// add two polynomials
// polyadd: float int -> float int -> float int
let rec polyadd ps qs =
match (ps, qs) with
| ([], ys) -> ys
| (xs, []) -> xs
| (x::xs, y::ys) -> (x+y)::polyadd xs ys
// polymul: float int -> float int -> float int
let rec polymul qs = function
| [] -> []
| p::ps -> polyadd (polymulconst p qs)
(polymulx (polymul qs ps))
let ( .++. ) p q = polyadd p q
let ( .**. ) p q = polymul p q
I tested the function in the F# REPL:
> let polyA = [1.0; -2.0; 1.0];;
val polyA : float list = [1.0; -2.0; 1.0]
> let polyB = [-4.0; 3.0; 2.0];;
val polyB : float list = [-4.0; 3.0; 2.0]
> polymul polyA polyB;;
val it : float list = [-4.0; 11.0; -8.0; -1.0; 2.0]
> polyA .**. polyB;;
val it : float list = [-4.0; 11.0; -8.0; -1.0; 2.0]
>

Pattern matching functions in OCaml

Can everyone explain to me this piece of code ?
let safe_division n = function
| 0 -> failwith "divide by 0"
| m -> n / m
When I excute safeDiv 3 0 , what is the m and n in this case ?
In general case, when does the function match the first and second pattern ?
It is easy to see what this means once you realise that
let f x y z = e
is just a short-hand for
let f = function x -> function y -> function z -> e
That is, a function of n arguments actually is n nested functions of 1 argument. That representation is called "currying". It is what allows you to apply a function partially, e.g.
let g = f 3
returns a function of 2 arguments.
Of course, the short-hand above can be mixed freely with the explicit form on the right, and that's what your example does. You can desugar it into:
let safe_division = function n -> function
| 0 -> failwith "divide by 0"
| m -> n / m
When you execute safe_division 3 0, first, 3 is bound to the name n and the right-hand side of the declaration is then evaluated.
This is a function, so the next argument, 0, is matched against the different cases, in order. Here, it matches the first case, so the right-hand side is evaluated and an exception is thrown. In this case, the name m is never bound to anything.
If the second argument was, for example, 1, then it would have matched the second case (this case matches every possible value anyway, it's a default case), binding the name m to the value 1 and then returning the result of n / m.
let safe_division n
define a function which type is int -> ...
function
| 0 -> failwith "divide by 0"
| m -> n / m
define a function which type is int -> int
So the resulting type of the whole is int -> int -> int where n is the first argument, and m the second. The last int is the result.
let safe_division n = function
| 0 -> failwith "divide by 0"
| m -> n / m
is just equivalent to:
let safe_division n = fun x -> match x with
| 0 -> failwith "divide by 0"
| m -> n / m
Note fun and function are slightly different. See: Function definition.

Resources