Ocaml Product of two polynomials - ocaml

How to compute the product of two polynomials ?
For example: x^3 + 3x^2 +0.2x and 2x^4 + 3
First I made a type
Type term = {coefficient:int; name:string; exponent:int};;
Type polynomials = term list;;
then I made a function calculate coefficient
let product l l' =
List.concat (List.map (fun e -> List.map (fun e' -> (e*e')) l'.coefficient)
l.coefficient);;
This is where I get stuck. I guess I can use the same function for exponent as well,but the question is asking writing a polynomials function with one param, which means two polynomials will be in the same variable
Can someone help me out here

You seem to be saying that you're asked to write a function to multiply two polynomials, but the function is supposed to have just one parameter. This, indeed, doesn't make a lot of sense.
You can always use a tuple to bundle any number of values into a single value, but there's no reason to do this (that I can see), and it's not idiomatic for OCaml.
Here's a function with one parameter (a pair) that multiplies two ints:
# let multiply (a, b) = a * b;;
val multiply : int * int -> int = <fun>
# multiply (8, 7);;
- : int = 56
(As a separate comment, the code you give doesn't compile.)

Related

Power function using multiplication and iteration in Standard ML

I am having trouble understanding a method to implement a power function in SML using only iteration and multiplication.
my iteration is the following:
fun iterate 0 f x = x
| iterate n f x = iterate (n-1) f (f x);
while my multiplication is basically iterating recursively
fun multiply 0 f = 0
| multiply f x = iterate x (fn x => x + 1) (multiply x (f-1));
Power function would basically be an iteration of the multiplication of the same base but I don't know which value to decrement
power n f = iterate (mult n n) (fn x => x + 1) (power (n) (f-1))
which is definately wrong
power n f = iterate (mult n n) (fn x => x + 1) (power (n) (f-1))
So, when it comes to naming, I might definitely write power x y or power i j or power x n or some such, since x, y, i, j or n look like they're numbers or integers, whereas f looks like it's a function. So right off the bat you have:
fun power x y = iterate (...a...) (...b...) (...c...)
As for what goes into each of these three parts, ...a..., ...b... and ...c...:
a. The thing iterate calls n, which is the number of times to iterate.
b. The thing iterate calls f, which is the function to apply each time.
c. The thing iterate calls x, which is what is applied each time.
As elaborated on in How to make a multiplication function using just addition function and iterate function in SML, there is no point in making power call itself; the point of using iterate is to hand over recursion to this list-combinator rather than use explicit recursion (where power has a reference to itself somewhere in its definition).

Standard ML: How to compute x to the power of i?

I am new to Standard ML. I am trying to compute x squared i, where x is a real and i is an non-negative integer. The function should take two parameters, x and i
Here is what I have so far:
fun square x i = if (i<0) then 1 else x*i;
The error that I am getting is that the case object and rules do not agree
The unary negation operator in SML is not - as it is in most languages, but instead ~. That is likely what is causing the specific error you cite.
That said, there are some other issues with this code. L is not bound in the example you post for instance.
I think you may want your function to look more like
fun square (x : real) 0 = 1
| square x i = x * (square x (i - 1))
You'll want to recurse in order to compute the square.

SML operator and operand do not agree

I am trying to write my first function in sml. It takes a tuple and returns the sum of first element times 10, second element times 6 and the third, and then divides by 10. I don't know what I am doing wrong here I get this error operator and operand do not agree [tycon mismatch].
fun rgb2gray(rgb: (int*int*int))=
let
val x = (#1rgb * 3 )+ (#2rgb * 6 )+ (#3rgb)
in
x=x/10
end
x=x/10 is an equality comparison (and will only be true if x is zero), and / is for dividing reals, not integers.
(+, -, and * are overloaded, but / isn't.)
Integer division is called div, and since the value of the function should be x div 10, you only need to write x div 10, without any =.
It's more common to use pattern matching than selectors for deconstructing structures, and I would write your function like this:
fun rgb2gray (r, g, b) = (r * 3 + g * 6 + b) div 10
Since molbdnilo already provided an answer, here is an alternative way you can do this using records:
type rgb = { r : int, g : int, b : int }
fun rgb2gray (color : rgb) : int =
(#r color * 3 +
#g color * 6 +
#b color) div 10
or equivalently by pattern matching on records:
fun rgb2gray ({ r = r, g = g, b = b } : rgb) : int =
(r * 3 + g * 6 + b) div 10
Records are like tuples, but where their parts are named rather than numbered (hence #r instead of #1). The syntax is a bit more fiddly, but the upside is that you don't accidentally mix two colors up as easily. Perhaps for RGB values it's hard to mix them up anyway, since the notion of R, G and B in that exact order is quite ingrained into a lot of programmers. Still, this is another option.
Since it appears that others have already helped you solve the problem I thought that I would point out that after the end you need an ; after it since the function is done.

Russian peasant exponentiation using tail-recursive OCaml

I tried the no tail recursion version of Russian Peasant exponentiation and it returned like this:
let rec fast_expNTR (base, power) =
match power with
|0->1
|n-> if n mod 2=0 then fast_expNTR (square base, power/2)
else base * fast_expNTR(square base , power/2)
But in else base*fast_expNTR(square base , power/2), it says expression is expected of type float but was given a type int. I don't understand the error.
Also, here is my attempt on tail-recursive fast exponentiation:
let fast_exp (base , power)=
let rec helper (acc ,acc2,p)=
if p=0 then acc * acc2
else if p mod 2 =0 then helper(int_of_float (square (float_of_int acc)),acc2, p/2)
else helper(int_of_float(square (float_of_int acc)),acc * acc2, p/2)
in helper(base,1,power)
But it didn't compute the correct result. Please help
Hint: Your function square has type float -> float and * is the integer multiplication.

Why does the exponential operator use float variables in OCaml?

Why does the exponential operator use float variables in OCaml?
Shouldn't it allow int variables too?
# 3**3;;
Error: This expression has type int but an expression was expected of type
float
Works:
# 3.0**3.0;;
- : float = 27.
So, the existing answers go into how to get around this, but not into why it is the case. There are two main reasons:
1) OCaml doesn't have operator aliasing. You can't have two operators that do the "same thing", but to different types. This means that only one kind of number, integers or floats (or some other representation) will get to use the standard ** interface.
2) pow(), the exponentiation function has historically been defined on floats (for instance, in Standard C).
Also, for another way to get around the problem, if you're using OCaml Batteries included, there is a pow function defined for integers.
You can use int
let int_exp x y = (float_of_int x) ** (float_of_int y) |> int_of_float
There's a similar question: Integer exponentiation in OCaml
Here's one possible tail-recursive implementation of integer exponentiation:
let is_even n =
n mod 2 = 0
(* https://en.wikipedia.org/wiki/Exponentiation_by_squaring *)
let pow base exponent =
if exponent < 0 then invalid_arg "exponent can not be negative" else
let rec aux accumulator base = function
| 0 -> accumulator
| 1 -> base * accumulator
| e when is_even e -> aux accumulator (base * base) (e / 2)
| e -> aux (base * accumulator) (base * base) ((e - 1) / 2) in
aux 1 base exponent