I tried doing a tail recursive function that will count the elements of a list, followed the rules, used an acumulator, but when I run it like this:
lstcountr [1..98765432];;
I get this:
System.OutOfMemoryException: Exception of type ‘System.OutOfMemoryException’ was thrown.
this is my function (which I thought is tail recursive /efficient):
let lstcountr ls =
let rec loop ls total =
match ls with
| [] -> total
| hd::tl -> loop tl total+1I
loop ls 0I
can this be done better ?
You function isn’t tail recursive.
Should be
Operators are interpreted after function calls, normally you can’t tell in situations like this because the results are identical, but that is not true with tail recursion.
Also as Tejs said, you are creating a list of too many items which is causing your
OutOfMemoryException. Have you tried using aseq { }?