Brackets in Okamla

I appreciate a very simple piece of code in Ocaml toplevel:

let p5 () = print_int 5;;
p5 ();;

print_string "*************************";;

let p4 = print_int 4;;
p4;; 

And it returns:

val p5 : unit -> unit = <fun>
#   5- : unit = ()
#   *************************- : unit = ()
#   4val p4 : unit = ()
#   - : unit = ()

My questions

  • What does mean ()in let p5 () = print_int 5;;?
  • What is the meaning -and ()in # 5- : unit = ()?
  • Is it a p4function?
  • Why does exist 4in the beginning # 4val p4 : unit = ()?
  • It seems like ()you can use Ocaml in your code to hide a side effect, can anyone show me an example?
+5
source share
4 answers

Here are some answers:

  • () - . - . , , . , OCaml - , , . , void C, ++ Java.
  • , . 5 print_int, . - : unit = () 5. , - unit ().
  • . , .
  • . 4 print_int. , p4, unit ().
  • , () . , , , - .
+11

LiKao , , , , , - . , , #.

# let p5 () = print_int 5;;
val p5 : unit -> unit = <fun>

p5 , unit unit. , (). , ( ). , (), , , . () ( , ).

# p5 ();;
5- : unit = ()

. 5 p5. - OCaml. , unit (). , print_int int -> unit.

# print_string "*************************";;
*************************- : unit = ()

. * print_string. , unit ().

# let p4 = print_int 4;;
4val p4 : unit = ()

. 4 print_int. , p4, unit (). , , print_int unit, () - . p4, . (->) . p4 - unit.

# p4;;
- : unit = ()

p4, (), p4 unit ().

+6

, () " ". , . :

 let p x = print_string "abc";;
 let q = print_string "abc";;

p q. , p 'a -> unit, q - unit. p, . "abc" p , .. p 1 p "blah" . ( p .) , p " " .

"x" "p x", "x" . "", "p" " p() =...". ,

 let p = fun () -> print_string "abc";;

"p" "p()". , , C, Java .., () . OCAML () - , " ", , "".

, q: "abc" , "print_string", q (), () - , "print_string".

+2

, , ()

let p5 () = print_int 5

Has pattern matching in argument p5. This is equivalent to this:

let p5 x = match x with () -> print_int 5

Or that:

let p5 = function () -> print_int 5

Or even this:

let p5 = fun x -> match x with () -> print_int 5

This difference is important in the following code:

let f (x, y) = print_int (x + y)
let g x y = print_int (x + y)

freceives only one parameter (pair (x, y)), and greceives two parameters. fthus has a type (int * int) -> unitbut ga type int -> int -> unit. Therefore, fit can be written as follows:

let f pair = match pair with (x, y) -> print_int (x + y)
0
source

All Articles