Created
August 23, 2021 15:46
-
-
Save FlandreDaisuki/dbc5463df3ac5cc55ae2746746559dc7 to your computer and use it in GitHub Desktop.
Why?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Student = struct | |
type t = { id: int; name: string; } | |
let init (id, name) = { id = id; name = name; } | |
end | |
;; | |
let alice = Student.init(0, "Alice") | |
(* val alice : Student.t = {Student.id = 0; name = "Alice"} *);; | |
let () = Printf.printf "Hello, %s\n" alice.name | |
;; | |
let () = List.iter (fun s -> | |
Printf.printf "Hello, %s\n" s.name | |
(* ^^^^ *) | |
(* Error: Unbound record field name *) | |
) [alice] | |
;; |
ohh, I get confused again when I meet the problem as following:
type student = { id: int; name: string; };;
let bob = { id = 1; name = "Bob"};;
(* val bob : student = {id = 1; name = "Bob"} *);;
let () = Printf.printf "Hello, %s\n" bob.name
;;
let () = List.iter (fun s ->
Printf.printf "Hello, %s\n" s.name
) [bob]
;;
It can be compiled and run as expected… why?
OK. According to the module section of Real World OCaml, we need open
the module signature.
We can expose it after module definition
module Student = struct
type t = { id: int; name: string; }
let init (id, name) = { id = id; name = name; }
end
;;
+ open Student;;
Or, expose it in minimum
- let () = List.iter (fun s ->
+ let () = let open Student in List.iter (fun s ->
Printf.printf "Hello, %s\n" s.name
) [alice]
;;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I get the point.
then
The
f
is not binding any type tox
until we pass a'a list
.There are 2 solutions to solve this by my knowledge:
and thank @yawaramin helps