(*redefining the power function for integers*)
let rec ( ** ) v n = if n = 0 then 1 else v * (( ** ) v (n-1));;
let rec sommation n =
if n = 0 then 0 else -1**(n/3) * n**(2+ (-1)**n) + sommation (n-1);;
print_int (sommation 7);;
When I run the above program in VS Code by selecting all lines of code then press Ctrl+Enter, this is what displays in the terminal:
└──────────────────────────────────────────────────────────────┘
Type #utop_help for help about using utop.
─( 17:07:51 )─< command 0 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # (*redefining the power function for integers*)
let rec ( ** ) v n = if n = 0 then 1 else v * (( ** ) v (n-1));;
val ( ** ) : int -> int -> int = <fun>
─( 17:07:51 )─< command 1 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop #
let rec sommation n =
if n = 0 then 0 else -1**(n/3) * n**(2+ (-1)**n) + sommation (n-1);;
val sommation : int -> int = <fun>
─( 17:07:54 )─< command 2 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop #
print_int (sommation 7);;
160- : unit = ()
─( 17:07:54 )─< command 3 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─
As you can see, it displays the lines of my program one after the other, which makes it take a long time to display the output which is 160
How can I fix this problem?
Once you start writing large programs rather than testing short snippets in the toplevel, it probably makes sense to save them as a file, and execute that file. If you go beyond one file, you should probably investigate using Dune to manage the build process.
Consider your example. Rather than a bunch of expressions separated by
;;tokens, let's put that into a filetest.ml.In a program, your last expression would not be valid. At the top level of a program, we cannot have bare expressions, so we bind it to
().Now you can execute this as
ocaml test.mlin your shell or compile it with ocamlc or ocamlopt.