{{ message }}

Instantly share code, notes, and snippets.

# moozzyk/float_conversion.ml

Last active Feb 4, 2018
Ocaml
 let is_prime n = let rec is_prime_aux n div = if div > int_of_float (sqrt n) then true else if n mod div = 0 then false else is_prime_aux n (div + 1) in is_prime_aux n 2 (* Error: This expression has type float but an expression was expected of type int Points to `n` in `if n mod div...` *) let is_prime n = let rec is_prime_aux n div = if div > int_of_float(sqrt (float_of_int n)) then true else if n mod div = 0 then false else is_prime_aux n (div + 1) in is_prime_aux n 2
 let sum a b = let s = a + b print_int (* Error: Syntax error *) let sum a b = let s = a + b in print_int s (* val sum : int -> int -> unit = *)
 print_int 2 + 3 (* Error: This expression has type unit but an expression was expected of type int *) print_int (2 + 3) (* Result: 5 *) print_string "a"^"b" (* Error: This expression has type unit but an expression was expected of type string *) print_string ("a"^"b") (* Result: ab *)
 print_int max 4 5 (* Error: This function has type int -> unit It is applied to too many arguments; maybe you forgot a `;'. *) print_int (max 4 5) (* Result: 5 *)
 let factorial n = if n = 0 then 1 else n * factorial(n - 1) (* Error: Unbound value factorial *) let rec factorial n = if n = 0 then 1 else n * factorial(n - 1) (* val factorial : int -> int = *)
 print_string "a" print_string "b" (* Error: This function has type string -> unit It is applied to too many arguments; maybe you forgot a `;'. *) print_string "a"; print_string "b" (* Result: ab *)
 print_int -5 (* Error: This expression has type int -> unit but an expression was expected of type int *) print_int (-5) (* Result: -5 *)
 let read_lines name : string list = let ic = open_in name in let try_read () = try Some (input_line ic) with End_of_file -> None in let rec loop acc = match try_read () with | Some s -> loop (s :: acc) | None -> close_in ic; List.rev acc in loop []
 let explode s = let rec exp i l = if i < 0 then l else exp (i - 1) (s.[i] :: l) in exp (String.length s - 1) []
 let sum list = List.fold_left (fun v a -> a + v) 0 list sum [1;2;3] "a" (* Error: This function has type int list -> int It is applied to too many arguments; maybe you forgot a `;'. *) sum [1;2;3] (* Result: 6 *)