How to write general integration function in OCaml - ocaml

I would like to write a function in OCaml that will calculate the definite integral for the given function. The problem is that I aim for the following syntax:
let sphere r phi theta = r *. sin phi *. cos theta in
let dphi = 10 in (* number of parts *)
let dtheta = 10 in (* number of parts *)
let zero = 0.0 in
let two_pi = 2.0 *. 3.14159
in
integral zero two_pi (integral zero two_pi (sphere 3.0) dphi) dtheta
The problem is that using rule like trapezoidal rule I need to write something like:
0.5 *. (f a +. f b) *. d
Which expects that the f a and f b are not partially applicated functions.
I don't expect that the result from the last integral function call will return me a float number, I'm totally fine with some functional.
I've realized that the question is very unspecific. Let me restate it in a more general way:
I have a function float->float->float which after the application of integral function should give me float->float. It should be general, so the integral of float->float should result in float.
The problem is that I need subtract two functions of the same order: f(a) -. f(b), where both of them could be float->float->float, float->float or even float->float->float.
To decrease the order of a function I need a signature like: (float->'a->float) -> ('a->float).
Is this even possible? Specifically in OCaml?
The more I think about this problem of having one function calculating the integral that can be chained, the more it seems like an impossible task/stupid way to do it.
In fact I've implemented this but using my own data type (called function_type which can be Scalar3rdOrderFunction, Scalar2ndOrderFunction, Scalar1stOrderFunction, Scalar0thOrderFunction). But for the prize of polymorphism the compiler cannot warn me when I try apply the integral three times for function float->float->float.

Related

How to make the modules conforming to the OCaml signatures

I am making a turtle graphics program by using ocaml. And this requires to provide an implementation of the module conforming to the following OCaml signature.
type program
type ins
val mf: float -> ins
val mb: float -> ins
val tl: float -> ins
val tr: float -> ins
val pu: ins
val pd: ins
val repeat: int -> program -> ins
val make_program: ins list -> program
type stroke
val strokes: program -> stroke list
type state
val animate: program -> state list
val strokes': program -> unit
val animate': program -> unit
Define a type for turtle programs and for turtle instructions.
The mf, mb, tl, tr, pu, pd, repeat and make_program functions are
used to build instructions and programs.
Define a type for strokes.
Program a function strokes that, given a turtle program, returns the
list of the strokes drawn by the turtle.
Define a type for the state of the turtle.
Program a function animate that, given a turtle program, returns the
list of states of the turtle.
The strokes' and animate' render the strokes and turtle animation
This is my code for mf, pu and pd:
type turtle = {
mutable x : float;
mutable y : float;
mutable phi : float;
mutable stt : int;
}
let round = int_of_float
let pi = 3.1415926535897932384626433832795
let rad_of_deg a = a *. pi /. 180.
let p = { x = 100.; y = 100.; phi = 0.; stt = 1 }
let pu() =
p.stt <- 0
let pd() =
p.stt <- 1
let mf l =
let x2 = (p.x) +. l *. cos (rad_of_deg p.phi)
and y2 = (p.y) +. l *. sin (rad_of_deg p.phi) in
moveto (round p.x) (round p.y);
if (p.stt == 1) then lineto (round x2) (round y2);
p.x <- x2;
p.y <- y2
The output of mf is:
val mf: float -> unit = <fun>
My question is how to make it look like the requirements?
I will try to give you a few hints, but you should consider to learn OCaml textbooks. I'm not going to teach you OCaml in a few keystrokes, not because I don't want to, but because it is impossible.
In OCaml a compilation unit consists of two parts:
module implementation
module signature
Module implementation consists of values and types, and each value has a type, associated with it. OCaml will infer types for values for you, but you can help it, using type annotations.
The implementation should be put in a file that has extension .ml. Signature should be put in a file with .mli extension. OCaml compiler will take them both, if they share the same name and build a compilation unit for you, that can be later linked into an executable.
For example you can put the given above signature into the file named gr.mli. Then you need to write a file that will implement this interface. You must name this file gr.ml and put your types and values into it. Then you can compile it using
ocamlbuild gr.cmo
and OCaml compiler will check whether your implementation actually implements the given signature. In order to conform to the signature, your module should contain all the values and types, specified in the signature and their types should be the same. Indeed, your implementation can contain more values, and types of values can be more general, than what is specified in a signature, but we're going to far away.
What you're showing in your example, (I'm refering to val mf: float -> unit = <fun>) is actually the output of the OCaml toplevel interpreter. And it consists of three parts (I use capital letter to denote that this is a variable part of the pattern):
val NAME : TYPE = VALUE
where NAME is a name of a value (in your case it is mf), TYPE is its inferred type (float -> unit in your case), and VALUE is a printable representation of the value. Since functions doesn't have a printable representation it is denoted as <fun> in your case. You can compare the type of your definition with the type of required definition (i.e., float -> ins). It isn't very hard to guess that this types can be equal if type ins is equal to type unit. Whether it is true depends on your implementation.
I hope, that this will help you. But this is not instead of reading textbooks. I'm just trying to give you starting hints.

FORTRAN 77 NEQNF IMSL Solver, 2 variables, 6 equations

I am trying to use NEQNF to solve a system of 6 non linear equations. I need to determine 2 variables to solve my system. According to description i need to define "N" which is the length of "X"(variables) AND "F"(equations).
Does this mean that i can use this solver only if X=F? Because N is defindes as an integer in the example given below in the description.
Or can i define N as a vector? How does declaration of N supposed to look like in this case?
From the link you gave:
X – The point at which the functions are evaluated. (Input) X should
not be changed by FCN.
F – The computed function values at the point X. (Output)
N — Length of X and F.
X and F are vectors of length N (scalar!). X is the input to FCN, and F the output. So I would guess that F is (generally) not equal to X.

subtract functions with type real in ml

I'm trying to subtract two functions(both with type real) in moscow ml. It then says "Overloaded - cannot be applied to arguments of type real -> real. So how should I write the function?
fun CircleArea x = x*x*Math.pi
fun SquareArea x:real = 4*x*x
fun Area x = SquareArea - CircleArea
You probably don't actually want to subtract one function from another, but the return values of those functions once they are applied. You could achieve this in the following way:
fun Area x = (SquareArea x) - (CircleArea x)
The parentheses are not mandatory, since function application (i.e. the space between SquareArea and x) binds tighter than any binary operator, including -.
You should consider using the following naming convention in ML: Regular functions have a lowercase starting symbol, while value constructors for algebraic types have uppercase starting symbols. For example:
fun area x = squareArea x - circleArea x
But:
datatype shape = Square of int * int
| Circle of int
Subtraction of functions like we have in mathematics isn't provided as a built-in operator. You can, however, define your own.
Mathematically speaking, we define
(f - g)(x) = f(x) - g(x)
We can replicate this definition in SML as follows:
infix 5 --
fun f -- g = fn x => f x - g x
What this does is produce an operator, --, such that f -- g produces the function corresponding to fn x => f x - g x, i.e. the function that given an x calculates f x - g x.
Note, due to the type-ambiguity in the - operator, it'll default to let you subtract 'a -> int functions. In your case you'll want to subtract 'a -> real functions, so you'll need a slight modification:
infix 5 --
fun f -- g = fn x => f x - g x : real
If you use this ---operator, you will be able to define your Area function like so:
val area = squareArea -- circleArea;
(I took the liberty of making the first letter of function names lowercase, to match the SML naming conventions.)

Ocaml fixed point implementation

I'm trying to figure out how to implement fixed point iteration in Ocaml. That is, given a function f and an x, I want to calculate what the final value of what f(f(f(x)...)) will be.
So for example, if my function is x/2 and my x=50, my answer should be 0.
So far, I have
let rec computed_fixed_point eq f x =
if (x == f x) then
x
else
computed_fixed_point eq f (f x)
This works for the function x/2 and x=50 (giving me 0), but for functions that go off to infinity or something other than 0, it doesn't seem to work.
Can another give me some advice? Thanks!
It's a little hard to understand the rationale of this problem. Not every function is going to have a fixed point. For example fun x -> (x + 1) mod 5. Not every function with a fixed point will reach the fixed point by repeated application from a distinct starting point. (I just did some googling, and fixed points like this are called "attractive fixed points".)
Here are some comments:
You shouldn't use ==, which is the physical equality operator. You possibly want to use =, equality of values.
However, I don't see what the eq parameter is for. Perhaps the caller is allowed to specify what equality to use. If so, you should use this instead of ==.

Overloading in Ocaml

I know that OCaml does not support overloading. Then, instead of overloading, what can we do to work this around?
1) use polymorphism instead?
2) give different functions different names?
3) put functions of the same name in different modules?
Which one will work?
It all depends on what you mean by overloading. There are several use cases, such as:
If you want to use the usual infix operators name in a mathematical expression manipulating something else than integers: rebind your operators locally; modules and "local open" can help with that.
module I32 = struct
open Int32
let (+), (-), ( * ), (/), (!!) = add, sub, mul, div, of_int
end
... I32.(x + y * !!2) ...
If you want an operation to be polymorphic in the type of numeric type being used, you need to abstract over such numeric operators. For example the generic fast exponentiation function (by an integer), that can be used on matrices etc.
let rec pow ( * ) one a = function
| 0 -> one
| n -> pow ( * ) (if n mod 2 = 0 then one else one * a) (a * a) (n / 2)
let () = assert (pow ( *.) 1. 2. 3 = 8.)
More generally, yes, the idea is to capture what you want to "overload" on as a set of operators (here infix operators but plain names are fine and often better for readability), and pass around and abstract over dictionaries of those operations -- much like what Haskell type classes are compiled to, in fact.