let set n v = Thread.delay 1.0; (n := v) in
let result1 x = set x (!x + 1) in
let result2 x = set x (!x * !x) in
let run i =
let original = 2 in
let r = ref (original) in
let t1 = Thread.create result1 r; let v1 = !r in
let v2 = !(result2 r) ;
Thread.join t1 ;
Printf.printf "number is %n" (v1 + v2) in
let main() =
run 1;
run 2 in
main() ;;
In the above program, I am using threads but could not figure out where the syntax error is. If anyone could help me to figure out what the error is.
This line:
let t1 = Thread.create result1 r; let v1 = !r in
Has two lets but only one in. I think you need another in here.
As a side comment, this is an unidiomatic way to structure your code at the top level of a file. It would be more usual to have a series of top-level definitions, which use let but not in. So it would look something like this:
let set n v = Thread.delay 1.0; (n := v)
let result1 x = set x (!x + 1)
let result2 x = set x (!x * !x)
let run i =
let original = 2 in
let r = ref (original) in
let t1 = Thread.create result1 r in
let v1 = !r in
let v2 = !(result2 r) in
Thread.join t1;
Printf.printf "number is %n" (v1 + v2)
let main () = run 1; run 2
let () = main ()
(I haven't compiled this so there might be a few syntax errors, apologies in advance. Just trying to show the basic layout.)
Related
I have this code in Ocaml
let double x = 2 * x
let triple x = 3 * x
let s = "Hello" in print_endline s
let () = triple 10 |> string_of_int |> print_endline
and when compiling with ocamlc file.ml this gives the error:
File "file.ml", line 5, characters 16-18:
Error: Syntax error
If I put ;; at the end of line 3 like this
let triple x = 3 * x;;
of if I comment characters 16-18 in line 5 like this
let s = "Hello" (* in print_endline s *)
the syntax error goes away.
Can someone explain the reason of the syntax error, and what each of these two corrections do to resolve it?
let s = "Hello" in print_endline s is not a top level declaration even if it starts with let, it's a let .. in expression. If you don't terminate the preceding expression with ;; it expects what comes next to be part of that expression instead of interpreting it as a top level declaration.
If you remove the in ... part you're changing it from a let ... in expression to a top level let declaration.
You can also turn it into a top level declaration like this:
let () = let s = "Hello" in print_endline s
Edit:
One way of thinking about this is, if instead of having
let triple x = 3 * x
let s = "Hello" in print_endline s
you replace let s = ... in ... with a simpler expression like just "Hello":
let triple x = 3 * x
"Hello"
This is equivalent to
let triple x = 3 * x "Hello"
which will be parsed as applying the argument "Hello" to the function x
This is my assignment.
(http://prnt.sc/aa3gwd)
I've been working on this one with a tutor and this is what we have come up with so far.
fun mult(a,b) =
let
val product = 0
in
if (a = 0) then
0
else
while a > 0 do
(
product := product + b;
if (a = 1) then
product
else
a:= a -1
);
end;
; //the function did not run at end;, so we added these two semicolons below
;
Output of this is:
stdIn:102.11-103.6 Error: syntax error: deleting SEMICOLON END SEMICOLON
I've only been introduced to SML in the last 2 weeks and I just can't get my head around it. Any help is very much appreciated.
You need two (mutable) reference variables; one for the product and one for the counter.
Something like this:
fun mult(a, b) =
let val product = ref 0
val counter = ref a
in
while !counter > 0 do (
product := !product + b;
counter := !counter - 1
);
!product
end;
(This isn't exactly a translation of the recursive code you linked to, because that code was unnecessarily complicated. You may need to adjust, depending on your professor.)
(I would write the recursive version more like this:
fun mult (0, _) = 0
| mult (_, 0) = 0
| mult (a, b) = b + mult(a - 1, b);
It's unclear why the exercise has a special case for a = 1.)
I'm working with objects in octave and I would like to call the superclass set method in the subclass set. In the GNU octave documentation I haven't found how its works so I've tried to use the matlab documentation syntax but I get the next error: '' undefined near line 20 column 5 where the call is.
¿How could I access the superclass method correctly?
Here the code:
function s = set (o, varargin)
s = o;
if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
error ([mfilename " :::: Expecting property/value pairs."]);
endif
while (length (varargin) > 1) #We get the first 2 pairs while exist.
prop = varargin{1};
val = varargin{2};
varargin(1:2) = [];
if (strcmp (prop, "color"))
if (ismember (val, ["black", "red", "green", "yellow", "blue", "violet", "cyan", "white"] )) #We check if val is a correct color.
s.color = val;
else
error ([mfilename " :::: Expecting the value for ""color"" to be a correct color."]);
endif
else
set#entity (s, prop,val);
endif
endwhile
endfunction
I'll add more details:
A simple example could be the next two classes:
try1, constructor and method (in his folder #try1):
function t = try1(x)
t.n = x;
t = class (t, "try1")
endfunction
function o = op(t,x)
o = t.n + x;
endfunction
try2 inherits from try1, constructor and method(in his folder #try2):
function t2 = try2(x)
t1 = #try1(x);
t.n = x;
t2 = class (t, "try2",t1);
endfunction
function o = op(t,x)
o = t.n - x;
endfunction
How to acces to op method of try1 with an instance of try2?
thanks :)
If you want to access the constructor of the parent class, just call it as you would normally outside the child class. Like so:
$ cat #try1/try1.m
function t = try1 (x)
t.n = x;
t = class (t, "try1");
endfunction
$ cat #try1/op.m
function o = op (t)
disp ("op() from try1");
o = t.n + 5;
endfunction
$ cat #try2/try2.m
function t2 = try2 (x)
t1 = #try1 (x);
t.n = x;
t2 = class (t, "try2", t1);
endfunction
$ cat #try2/op.m
function o = op (t)
o = op (t.t1);
endfunction
$ octave
octave:1> try2 (5)
ans = <class try2>
octave:2> op (ans)
op() from try1
ans = 10
See the manual section on Object Oriented Programming, specially the section on Inheritance and Aggregation
I need a function that produces primes in F#. I found this:
let primesSeq =
let rec nextPrime n p primes =
if primes |> Map.containsKey n then
nextPrime (n + p) p primes
else
primes.Add(n, p)
let rec prime n primes =
seq {
if primes |> Map.containsKey n then
let p = primes.Item n
yield! prime (n + 1) (nextPrime (n + p) p (primes.Remove n))
else
yield n
yield! prime (n + 1) (primes.Add(n * n, n))
}
prime 2 Map.empty
This works very well, but sometimes I need to work with int64/BigInts as well. Is there a more clever way of reusing this code than providing another sequences like these:
let primesSeq64 = Seq.map int64 primesSeq
let primesBigInts = Seq.map (fun (x : int) -> BigInteger(x)) primesSeq
I've heard about modifying a code using "inline" and "LanguagePrimitives", but all I've found was connected with function while my problem is related to a value.
Moreover - I'd like to have a function that works with integer types and computes a floor of a square root.
let inline sqRoot arg = double >> Math.Sqrt >> ... ?
but I can't see a way of returning the same type as "arg" is, as Math.Sqrt returns a double. Again - is there anything better than reimplementing the logic that computes a square root by myself ?
So the general way to do this requires a function and languageprimitives - in your case everywhere you have 1 you write LanguagePrimitives.GenericOne which will produce 1 or 1.0 etc depending on what is required.
To get this to work, you need to create a function value - you can avoid this by doing something like:
let inline primesSeq() = ...
let primesintSeq = primesSeq() //if you use this as an int seq later the compiler will figure it out, otherwise you use
let specified : int seq = primesSeq()
I am not so sure about the sqrt case though - it probably depends on how hacky you are willing to make the solution.
A naïve implementation of generic sqRoot may go along these lines:
let sqRoot arg =
let inline sqrtd a = (double >> sqrt) a
let result = match box(arg) with
| :? int64 as i -> (sqrtd i) |> int64 |> box
| :? int as i -> (sqrtd i) |> int |> box
// cases for other relevant integral types
| _ -> failwith "Unsupported type"
unbox result
and then, checking in FSI:
> let result: int = sqRoot 4;;
val result : int = 2
> let result: int64 = sqRoot 9L;;
val result : int64 = 3L
I have a recursive function fact, which can be called from either an expression inside it or an expression outside it.
I would like to associate fact with a variable v, such that each time fact is called from outside (another function), v is initialized, and its value can be changed inside fact, but never can be initialized when fact is called from inside.
The following code suits my need, but one problem is that v is defined as a global variable, and I have to do v := init before calling fact from outside, which I do not find beautiful.
let init = 100
let v = ref init
let rec fact (n: int) : int =
v := !v + 1;
if n <= 0 then 1 else n * fact (n - 1)
let rec fib (n: int) : int =
if n <= 0 then 0
else if n = 1 then (v := !v + 50; 1)
else fib (n-1) + fib (n-2)
let main =
v := init;
print_int (fact 3);
print_int !v; (* 104 is expected *)
v := init;
print_int (fib 3);
print_int !v;; (* 200 is expected *)
Could anyone think of a better implementation?
You can hide the function and value definitions within the body of a containing function as follows:
open Printf
let init = 100
let fact n =
let rec fact counter n =
incr counter;
if n <= 0 then 1 else n * fact counter (n - 1)
in
let counter = ref init in
let result = fact counter n in
(result, !counter)
let main () =
let x, count = fact 3 in
printf "%i\n" x;
printf "counter: %i\n" count (* 104 is expected *)
let () = main ()
You can adapt Martin's solution so that data is shared across various calls:
let fact =
let counter = ref 0 in
fun n ->
let rec fact = ... in
fact n
The idea is to transform let fact = fun n -> let counter = ... in ... into let fact = let counter = ... in fun n -> ...: counter is initialized once, instead of at each call of fact.
A classical example of this style is:
let counter =
let count = ref (-1) in
fun () ->
incr count;
!count
Beware however that you may get into typing trouble if the function was meant to be polymorphic: let foo = fun n -> ... is always generalized into a polymorphic function, let foo = (let x = ref ... in fun n -> ...) is not, as that would be unsound, so foo won't have a polymorphic type.
You can even generalize the counter example above to a counter factory:
let make_counter () =
let count = ref (-1) in
fun () ->
incr count;
!count
For each call to make_counter (), you get a new counter, that is a function that shares state across call, but whose state is independent from previous make_counter () counter creations.
With Ocaml's objects, you can do:
class type fact_counter = object ('self)
method get : int
method set : int -> unit
method inc : unit
method fact : int -> int
end;;
class myCounter init : fact_counter = object (self)
val mutable count = init
method get = count
method set n = count <- n
method inc = count <- count + 1
method fact n =
self#inc;
if n <= 0 then 1 else n * self#fact (n - 1)
end;;
Then you can obtain:
# let c = new myCounter 0;;
val c : myCounter = <obj>
# c#fact 10;;
- : int = 3628800
# c#get;;
- : int = 11
# c#set 42;;
- : unit = ()
# c#fact 10;;
- : int = 3628800
# c#get;;
- : int = 53
I hope you can easily see how to adapt myCounter to include fib ...