SML: Creating Abstract Data Types - sml

I'm writing a simple Abstract Data Type for fractions and
I cant even get the constructor to work, I'm just very lost on SML syntax.
signature fracs = sig
type fraction
exception zero_denominator
(* constructor *)
val // : int * int -> fraction
/*******************************************************************************************************************************************/
that is the .sig file showing the constructor that i am implementing.
Here is what i have so far. the error i recieve is that I'm doing int*int* -> int
when i want int*int-> fraction. I know what its saying and everything, but I just cant make it happen.
structure fracs :> fracs = struct
abstype fraction = frac of int * int
with
exception zero_denominator;
(**********************************)
(*constructor*)
infix 8 //;
fun num // den = if den = 0 then raise zero_denominator
else
num * den;
end;(*end ADT*)
end;(*end struct*)

In function signature, A * B means a tuple with two elements of types A and B. However in implementation, A * B means multiplication between two integers.
What you want is to make a fraction value from two integers:
fun num // den =
if den = 0 then raise zero_denominator else frac(num, den)

Related

Writing power function in Standard ML with a predefined compound function

Having trouble writing a power function inStandard Ml. Im trying to write a function called exp of type int -> int -> int.
The application exp b e, for non-negative e, should return b^e.
For example, exp 3 2 should return 9. exp must be implemented with the function compound provided below. exp should not directly calls itself. Here is the compound function, it takes in a value n, a function, and a value x. All it does is it applies the function to the value x n number of times.
fun compound 0 f x = x
| compound n f x = compound (n-1) f (f x);
Im having trouble figuring out how to write this function without recursion, and with the restraint of having to use a function that only can use a function with one parameter. Anyone have any ideas of where to start with this?
This is what I have:
fun exp b 0 = 1
| exp b e = (compound e (fn x => x*x) b)
I know that this doesn't work, since if i put in 2^5 it will do:
2*2, 4*4, 16*16 etc.
You are extremely close. Your definition of exp compounds fn x => x*x which (as you noticed) is not what you want, because it is repeatedly squaring the input. Instead, you want to do repeated multiplication by the base. That is, fn x => b*x.
Next, you can actually remove the special case of e = 0 by relying upon the fact that compound "does the right thing" when asked to apply a function 0 times.
fun exp b e = compound e (fn x => b*x) 1
You could just do this instead I believe
fun exp 0 0 = 1
| exp b 0 = 1
| exp b e = (compound (e - 1) (fn x => b * x ) b);
this may not be exactly 100% proper code. I sort of just now read a bit of Standard ML documentation and took some code and reworked it for your example but the general idea is the same for most programming languages.
fun foo (num, power) =
let
val counter = ref power
val total = 1
in
while !counter > 0 do (
total := !total * num
counter := !counter - 1
)
end;
To be more clear with some pseudo-code:
input x, pow
total = 1
loop from 1 to pow
total = total * x
end loop
return total
This doesn't handle negative exponents but it should get you started.
It basically is a simple algorithm of what exponents truly are: repeated multiplication.
2^4 = 1*2*2*2*2 //The 1 is implicit
2^0 = 1

Sum of digits in an integer using SML

I'm trying to create a function that will sum the digits of an integer in SML but I'm getting the following error.
Error: operator and operand don't agree [overload conflict]
operator domain: real * real
operand: [* ty] * [* ty]
in expression:
n / (d * 10)
I've tried to typecast the variables to real but it didn't work. Also I don't understand why I'm getting this error. Is not possible to use operators such as * and / with int and real in SML?
The code is the following:
fun sumDigits (n) =
if n < 10 then n
else
let
val d = 10
in
n mod d + sumDigits(trunc(n/(d*10)))
end
Looks like you have a few things wrong. To start, you'll want to use "div" rather than "/" when dividing integers. / is for reals. Also, trunc is a function for reals. 3rd, you'll want your recursive logic to just be sumDigits(n div 10), not sumDigits(n div (d*10)). You can also clean up the code by removing the d variable.
fun sumDigits (n) =
if n < 10 then n
else
n mod 10 + sumDigits(n div 10)

using Friend function and operator+ to add class variables and print out

I've written a code which takes an input of 3 integers (integer, numerator and denominator) and displays them as "a{b/c}"
I have defined/declared a class (fraction) which contains these 3 separate integer variables and the functions to read and print them.
In order to store several of these different outputs, I've created a dynamic array of the class type defined.
I would like to sum all the values together eg
fract[0].a + frac[1].a .. etc for the integer part and find the sum of the fraction part as well and then display this.
for the class declaration I have included a friend function:
friend fraction operator +(fraction, fraction);
I have also declared 2 dynamic arrays of type fraction
fraction* fracarry = new fraction[x];
fraction* fractot = new fraction[1];
fracarry stores the input fractions, fractot is initialized as:
numerator = 0;
denominator = 1;
integral = 0;
The definition of the friend function is as follows:
fraction operator+(fraction, fraction)
{
for(int i = 0; i < x; i++)
{
fractot[0].denominator += fracarry[i].denominator*fractot[0].denominator;
fractot[0].integral += fracarry[i].integral;
fractot[0].numerator += ((fracarry[i].numerator*fractot[0].denominator) + (fractot[0].numerator*fracarry[i].denominator));
}
return fractot[0];
}
where x is an input from the user for how many fractions will be entered.
The main function is:
cout << " Please input how many fractions you will be inputting: " << endl;
cin >> x;
fraction *fracarry = new fraction[x];
fraction *fractot = new fraction[1];
fracarry[0].read();
fractot[0] = fractot[0] + fracarry[0];
fractot[0].print2();
I'm not sure if I should have the loop in the function definition or the main function. It complies and the read/print functions work but I can't get it to display fractot.print2() as the final sum of the values stored in fracarry
I don't want exact code, just any hints of where I may have gone wrong/what to look up, or any tutorials that might help etc
Thanks!
**edit
This is the same question as asked but I tried to cut down the irrelevant code/ make it more logical as requested!
i think your problem is in these lines:
fractot[0].integral =+ fracarry[j].integral;
fractot[0].numerator =+ fracarry[j].numerator;
in order to summing a parameter with its own value you must write it this way:+=

GCD in OCaml ( beginner )

I want to write this simple code :
let rec gcd a b =
if b = 0 then a else gcd b (a mod b);;
val gcd : int -> int -> int = <fun>
Printf.printf "%d da \n" gcd 55 200 ;;
This is the code , the error I get is :
File "tst.ml", line 3, characters 0-3:
Error: Syntax error
And also , can anyone explain to me what is that " int -> int -> int = " all about ? I know that it must be something about the parameters and the returned value of the function but what and how ? :)
You're passing gcd 55 and 200 as separate parameters of printf. So, try this:
Printf.printf "%d da\n" (gcd 55 200);;
It looks like you did some copy & paste from an ocaml interactive session, since normally we don't mix up function definitions (the 2 first lines), and function declarations (the third line, though in this case it looks more like the answer of the ocaml interpreter when provided with the definition - because of the <fun> part which isn't syntactically correct in a program, but is used by the interpreter to indicate that it figured out that the value is a function) in the same scope.
So, you should not include that third line, and you will have to fix the last instruction, as #JeffreyScofield explained.
(* gcd function definition *)
let rec gcd a b =
if b = 0 then a else gcd b (a mod b);;
(* val gcd: int -> int -> int *)
Printf.printf "%d da \n" (gcd 55 200);;
Alternatively, the last line could be written:
Printf.printf "%d da \n" ## gcd 55 200;;
The function signature you included by mistake indicates that gcd takes a sequence of 2 integer parameters, and returns an integer. The notation is said to be in curried form: each parameter passed to a function A yields another function B expecting the remaining parameters of A. Thus you can read that signature several ways:
As a function taking 2 integers and returning one,
val gcd: int -> int -> int
As a function taking an integer, and returning an a function, which takes an integer and returns an integer.
val gcd: int -> (int -> int)
Both notations are equivalent (The arrow "operator" is said to be associative on the right), but the second one helps to understand this idea of function return "chaining".
In int -> int -> int:
The last int is the return value
The first two ints are the parameters
Consider reading this to understand function types.

obtain the integer from a model after s.get_model()

In Z3's C++ API, I can search for a model by
model m = s.get_model();
Then:
cout << m.eval(A);
will give me the value for A.
However, m.eval(A) returns an expr object but I want to store A's value as an integer in my program. How can I convert an expr to an int?
This exact question has come up before; perhaps these help to clarify: Q1 Q2
The C API exposes methods for retrieving integer values from expressions that are integers.
The most general API is:
/**
\brief Return numeral value, as a string of a numeric constant term
\pre Z3_get_ast_kind(c, a) == Z3_NUMERAL_AST
def_API('Z3_get_numeral_string', STRING, (_in(CONTEXT), _in(AST)))
*/
Z3_string Z3_API Z3_get_numeral_string(__in Z3_context c, __in Z3_ast a);
It returns a string (char*). This allows returning bignums (numerals that don't fit in 64 bits).
Z3 exposes a set of other Z3_get_numeral variants for special cases. These are documented in z3_api.h, or see: http://research.microsoft.com/en-us/um/redmond/projects/z3/code/group__capi.html
Possible example using Z3py
x= Int('x')
s = Solver()
s.add(x + 3 == 5)
print s.check()
m = s.model()
print m
y = (m.evaluate(x))
z = y + 4
print simplify(z)
Output:
sat
[x = 2]
6