Standard ML Fibonacci Overflow

I was busy learning functional programming and decided to take the ML as my car to do this. It has only been a few days since I raised ML and perhaps spent about 5-6 hours working on some problems. Anyway, on my problem.

Typically, as I study the language, I look at a few questions from the project eulers to get an idea of ​​the syntax and actions. Therefore, I worked on a problem that requires a factor function. Although I continue to get an overflow error, usually to solve this problem in other languages, I would add some memos or rely on standard libraries to avoid this, but my inexperience with ML makes my memories seem foreign.

I tried something like this using tail recursion but not a cube:

fun fact_helper (0,r:int) = r
| fact_helper (n:int,r:int) = fact_helper (n-1,n*r);

fun factorial n:int = fact_helper(n, 1);

Even using standard libraries:

foldl op * 1 (List.tabulate(100, fn x => x + 1))

will lead to overflow.

I did some search queries, but ML seems to have very rare discussions or community. Therefore, I think that my question is an example or how should I write my factorial function in a memoized way or how to avoid overflow in ML in general.

+4
source share
1 answer

, Int.int, SML/NJ 31 (. Int.precision). , , . , Overflow:

- (Option.valOf Int.maxInt) + 1;

uncaught exception Overflow [overflow]
  raised at: <file stdIn>

IntInf, :

open IntInf;

fun fact_helper (0,r:int) = r
  | fact_helper (n:int,r:int) = fact_helper (n-1,n*r);

fun factorial n:int = fact_helper(n, 1);

factorial 50;
(* 30414093201713378043612608166064768844377641568960512000000000000 *)
+6

Source: https://habr.com/ru/post/1656743/


All Articles