SML: Determining Type of Function - functional-programming

Suppose all I know about a function is that it is of type:
int list -> int * string -> int
Is there any way of knowing in advance whether this means:
(int list -> int * string) -> int or int list -> (int * string -> int)?
Thanks,
bclayman

-> is right associative in SML type annotations, so int list -> (int * string -> int) is correct.
Consider this simple experiment in the REPL:
- fun add x y = x+y;
val add = fn : int -> int -> int
add is a function which, when fed an int, returns a function, namely the function which sends y to x + y -- hence its type is int -> (int ->int). It isn't a function which, when a fed a function from ints to ints outputs an int (which is what (int -> int) -> int would be). A somewhat artificial example of the later sort of thing is:
- fun apply_to_zero_and_increment f = 1 + f(0);
val apply_to_zero_and_increment = fn : (int -> int) -> int
If I define fun g(x) = x + 5 then apply_to_zero_and_increment g returns 6.

Related

Like Bezout's identity but with Natural numbers and an arbitrary constant. Can it be solved?

I'm an amateur playing with discrete math. This isn't a
homework problem though I am doing it at home.
I want to solve ax + by = c for natural numbers, with a, b and c
given and x and y to be computed. I want to find all x, y pairs
that will satisfy the equation.
This has a similar structure to Bezout's identity for integers
where there are multiple (infinite?) solution pairs. I thought
the similarity might mean that the extended Euclidian algorithm
could help here. Below are two implementations of the EEA that
seem to work; they're both adapted from code found on the net.
Could these be adapted to the task, or perhaps can someone
find a more promising avenue?
typedef long int Int;
#ifdef RECURSIVE_EEA
Int // returns the GCD of a and b and finds x and y
// such that ax + by == GCD(a,b), recursively
eea(Int a, Int b, Int &x, Int &y) {
if (0==a) {
x = 0;
y = 1;
return b;
}
Int x1; x1=0;
Int y1; y1=0;
Int gcd = eea(b%a, a, x1, y1);
x = y1 - b/a*x1;
y = x1;
return gcd;
}
#endif
#ifdef ITERATIVE_EEA
Int // returns the GCD of a and b and finds x and y
// such that ax + by == GCD(a,b), iteratively
eea(Int a, Int b, Int &x, Int &y) {
x = 0;
y = 1;
Int u; u=1;
Int v; v=0; // does this need initialising?
Int q; // quotient
Int r; // remainder
Int m;
Int n;
while (0!=a) {
q = b/a; // quotient
r = b%a; // remainder
m = x - u*q; // ?? what are the invariants?
n = y - v*q; // ?? When does this overflow?
b = a; // A candidate for the gcd - a's last nonzero value.
a = r; // a becomes the remainder - it shrinks each time.
// When a hits zero, the u and v that are written out
// are final values and the gcd is a's previous value.
x = u; // Here we have u and v shuffling values out
y = v; // via x and y. If a has gone to zero, they're final.
u = m; // ... and getting new values
v = n; // from m and n
}
return b;
}
#endif
If we slightly change the equation form:
ax + by = c
by = c - ax
y = (c - ax)/b
Then we can loop x through all numbers in its range (a*x <= c) and compute if viable natural y exists. So no there is not infinite number of solutions the limit is min(c/a,c/b) ... Here small C++ example of naive solution:
int a=123,b=321,c=987654321;
int x,y,ax;
for (x=1,ax=a;ax<=c;x++,ax+=a)
{
y = (c-ax)/b;
if (ax+(b*y)==c) here output x,y solution somewhere;
}
If you want to speed this up then just iterate y too and just check if c-ax is divisible by b Something like this:
int a=123,b=321,c=987654321;
int x,y,ax,cax,by;
for (x=1,ax=a,y=(c/b),by=b*y;ax<=c;x++,ax+=a)
{
cax=c-ax;
while (by>cax){ by-=b; y--; if (!y) break; }
if (by==cax) here output x,y solution somewhere;
}
As you can see now both x,y are iterated in opposite directions in the same loop and no division or multiplication is present inside loop anymore so its much faster here first few results:
method1 method2
[ 78.707 ms] | [ 21.277 ms] // time needed for computation
75044 | 75044 // found solutions
-------------------------------
75,3076776 | 75,3076776 // first few solutions in x,y order
182,3076735 | 182,3076735
289,3076694 | 289,3076694
396,3076653 | 396,3076653
503,3076612 | 503,3076612
610,3076571 | 610,3076571
717,3076530 | 717,3076530
824,3076489 | 824,3076489
931,3076448 | 931,3076448
1038,3076407 | 1038,3076407
1145,3076366 | 1145,3076366
I expect that for really huge c and small a,b numbers this
while (by>cax){ by-=b; y--; if (!y) break; }
might be slower than actual division using GCD ...

Propositional Logic Valuation in SML

I'm trying to define a propositional logic valuation using SML structure. A valuation in propositional logic maps named variables (i.e., strings) to Boolean values.
Here is my signature:
signature VALUATION =
sig
type T
val empty: T
val set: T -> string -> bool -> T
val value_of: T -> string -> bool
val variables: T -> string list
val print: T -> unit
end;
Then I defined a matching structure:
structure Valuation :> VALUATION =
struct
type T = (string * bool) list
val empty = []
fun set C a b = (a, b) :: C
fun value_of [] x = false
| value_of ((a,b)::d) x = if x = a then b else value_of d x
fun variables [] = []
| variables ((a,b)::d) = a::(variables d )
fun print valuation =
(
List.app
(fn name => TextIO.print (name ^ " = " ^ Bool.toString (value_of valuation name) ^ "\n"))
(variables valuation);
TextIO.print "\n"
)
end;
So the valuations should look like [("s",true), ("c", false), ("a", false)]
But I can't declare like a structure valuation or make an instruction like: [("s",true)]: Valuation.T; When I tried to use the valuation in a function, I get errors like:
Can't unify (string * bool) list (*In Basis*) with
Valuation.T
Could someone help me? Thanks.
The type Valuation.T is opaque (hidden).
All you know about it is that it's called "T".
You can't do anything with it except through the VALUATION signature, and that signature makes no mention of lists.
You can only build Valuations using the constructors empty and set, and you must start with empty.
- val e = Valuation.empty;
val e = - : Valuation.T
- val v = Valuation.set e "x" true;
val v = - : Valuation.T
- val v2 = Valuation.set v "y" false;
val v2 = - : Valuation.T
- Valuation.value_of v2 "x";
val it = true : bool
- Valuation.variables v2;
val it = ["y","x"] : string list
- Valuation.print v2;
y = false
x = true
val it = () : unit
Note that every Valuation.T value is printed as "-" since the internal representation isn't exposed.

How to pattern match on input tuples ocaml

For example, I have the code
let add_next (data: int * int * int list) : int =
However,the word data is really ambiguous, and I'd like to be able to name the first two integers and then the list in the function header, while preserving the type of int * int * int list. How can this be done?
OCaml version 4.01.0
# let add_next ((first, second, l): int * int * int list) : int = first;;
val add_next : int * int * int list -> int = <fun>
If you need to pass the data tuple around without having to rebuild it, use the as construct:
# let add_next ((first, second, l) as data: int * int * int list) : int =
ignore data;
first;;
val add_next : int * int * int list -> int = <fun>

How to use map in a function

The function in map is pretty easy. I want to double every element in a list which can be done:
map(fn x => x * 2);
But what if I want to name this function double?
fun double = map(fn x => x * 2);
Calling this function I get
- double [1,2,3];
val it = fn : int list -> int list
How can I name this function double?
The result of map (fn x => x * 2) is a function, which can be bound to an identifier:
- val double = map (fn x => x * 2);
val double = fn : int list -> int list
- double [1,2,3];
val it = [2,4,6] : int list
The fun form is just syntactic sugar. For example:
fun name param = ...
will be desugared to:
val rec name = fn param => ...
The rec part is a keyword that lets you implement recursive function definitions.

What are the performance side effects of defining functions inside a recursive function vs outside in F#

If you have a recursive function that relies on some other function what is the preferred way to implement that?
1) outside the recursive function
let doSomething n = ...
let rec doSomethingElse x =
match x with
| yourDone -> ...
| yourNotDone -> doSomethingElse (doSomething x)
2) inside the recursive function
let rec doSomethingElse x =
let doSomething n = ...
match x with
| yourDone -> ...
| yourNotDone -> doSomethingElse (doSomething x)
3) encapsulate both inside the a third function
let doSomethingElse x =
let doSomething n = ...
let innerDoSomethingElse =
match x with
| yourDone -> ...
| yourNotDone -> innerDoSomethingElse (doSomething x)
4) something even better?
module Test =
let f x =
let add a b = a + b //inner function
add x 1
let f2 x =
let add a = a + x //inner function with capture, i.e., closure
add x
let outerAdd a b = a + b
let f3 x =
outerAdd x 1
Translates to:
[CompilationMapping(SourceConstructFlags.Module)]
public static class Test {
public static int f(int x) {
FSharpFunc<int, FSharpFunc<int, int>> add = new add#4();
return FSharpFunc<int, int>.InvokeFast<int>(add, x, 1);
}
public static int f2(int x) {
FSharpFunc<int, int> add = new add#8-1(x);
return add.Invoke(x);
}
public static int f3(int x) {
return outerAdd(x, 1);
}
[CompilationArgumentCounts(new int[] { 1, 1 })]
public static int outerAdd(int a, int b) {
return (a + b);
}
[Serializable]
internal class add#4 : OptimizedClosures.FSharpFunc<int, int, int> {
internal add#4() { }
public override int Invoke(int a, int b) {
return (a + b);
}
}
[Serializable]
internal class add#8-1 : FSharpFunc<int, int> {
public int x;
internal add#8-1(int x) {
this.x = x;
}
public override int Invoke(int a) {
return (a + this.x);
}
}
}
The only additional cost for an inner function is new'ing up an instance of FSharpFunc--seems negligible.
Unless you're very performance sensitive, I would go with the scope that makes the most sense, that is, the narrowest scope possible.

Resources