Define a static variable for a recursive function in OCaml - variables

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 ...

Related

Is "variable dot property" construct (var.property) just syntaxic sugar for accessors?

This is a follow up question to this one: Are accessors of class properties useful?
In this complete answer it is stated that:
"When you use the property, you are using the getter and setter methdods. The property is a convenience for language binding. Thus, we could also say that you don't need the property, only the getter and setter."
But the following experiment seems to contradict that point:
file src/PositiveInteger.gd
With a setter which prevents negative integer to be assigned to the property n
class_name PositiveInteger
var n: int
func _init() -> void:
self.n = 0
func set_n(_n: int) -> void:
if _n < 0:
n = 0
else:
n = _n
func get_n() -> int:
return n
file main.gd
Now let us consider this test, with c1 using the setter and c2 using the dot construct:
tool
extends EditorScript
tool
extends EditorScript
func _run() -> void:
var PositiveInteger = load("res://src/PositiveInteger.gd")
var c1 = PositiveInteger.new()
c1.set_n(-3)
print("c1: " + str(c1.n))
var c2 = PositiveInteger.new()
c2.n = -3
print("c2: " + str(c2.n))
The output is:
c1: 0
c2: -3
So the property assignement seems to bypass the setter, is this behaviour different with the core class of the language only?
My prior answer applies to core classes (and should apply to modules classes), which are written in C++. They do not expose anything by default. Instead they must bind their C++ methods as methods and properties to expose them.
Now, if you want something like that for a class created in GDScript, you can do it with setget:
class_name PositiveInteger
var n: int setget set_n, get_n
func _init() -> void:
self.n = 0
func set_n(_n: int) -> void:
if _n < 0:
n = 0
else:
n = _n
func get_n() -> int:
return n
With that your output should be:
0
0

Why does `variable++` increment the variable but `variable + 1` does not?

Here's the problem in which I encountered this issue:
The function should compare the value at each index position and score a point if the value for that position is higher. No point if they are the same. Given a = [1, 1, 1] b = [1, 0, 0] output should be [2, 0]
fun compareArrays(a: Array<Int>, b: Array<Int>): Array<Int> {
var aRetVal:Int = 0
var bRetVal:Int = 0
for(i in 0..2){
when {
a[i] > b[i] -> aRetVal + 1 // This does not add 1 to the variable
b[i] > a[i] -> bRetVal++ // This does...
}
}
return arrayOf(aRetVal, bRetVal)
}
The IDE even says that aRetVal is unmodified and should be declared as a val
What others said is true, but in Kotlin there's more. ++ is just syntactic sugar and under the hood it will call inc() on that variable. The same applies to --, which causes dec() to be invoked (see documentation). In other words a++ is equivalent to a.inc() (for Int or other primitive types that gets optimised by the compiler and increment happens without any method call) followed by a reassignment of a to the incremented value.
As a bonus, consider the following code:
fun main() {
var i = 0
val x = when {
i < 5 -> i++
else -> -1
}
println(x) // prints 0
println(i) // prints 1
val y = when {
i < 5 -> ++i
else -> -1
}
println(y) // prints 2
println(i) // prints 2
}
The explanation for that comes from the documentation I linked above:
The compiler performs the following steps for resolution of an operator in the postfix form, e.g. a++:
Store the initial value of a to a temporary storage a0;
Assign the result of a.inc() to a;
Return a0 as a result of the expression.
...
For the prefix forms ++a and --a resolution works the same way, and the effect is:
Assign the result of a.inc() to a;
Return the new value of a as a result of the expression.
Because
variable++ is shortcut for variable = variable + 1 (i.e. with assignment)
and
variable + 1 is "shortcut" for variable + 1 (i.e. without assignment, and actually not a shortcut at all).
That is because what notation a++ does is actually a=a+1, not just a+1. As you can see, a+1 will return a value that is bigger by one than a, but not overwrite a itself.
Hope this helps. Cheers!
The equivalent to a++ is a = a + 1, you have to do a reassignment which the inc operator does as well.
This is not related to Kotlin but a thing you'll find in pretty much any other language

Tail Recursion and Iteration SML

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.)

Generalizing functions in F#

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

ocaml - function without args and global variables

I have a task to do in ocaml and can't find any help information so ask here ;) How to define function which give us something other in each call without using global variables ? I would like to do fun next() which return next odd numbers or next values of factorial.
Like this
# next();;
- : int = 1
# next();;
- : int = 3
# next();;
- : int = 5
# next();;
- : int = 7
Do you have any tips for me ?
Thanks in advance
Greg
let next =
let private_counter = ref (-1) in
fun () ->
private_counter := !private_counter + 2;
!private_counter
You can also encapsulate this in a "counter factory":
let make_counter () =
(* note the () parameter : at each call of make_counter(),
a new "next function" with a fresh counter is generated *)
let private_counter = ...