fork download
  1.  
  2. class person_a (name : string) (age : int) = object
  3.  
  4. method serialize_to_string =
  5. Printf.sprintf "{ name = \"%s\" ; age = %d }" name age (* depends on format *)
  6.  
  7. end
  8.  
  9. let example_a () =
  10. let p = new person_a "John Smith" 30 in
  11. Printf.printf "person_a : %s\n" p#serialize_to_string
  12.  
  13.  
  14.  
  15. type value =
  16. | Int of int
  17.  
  18. type property = string * value
  19.  
  20. class person_b (name : string) (age : int) = object
  21.  
  22. method serialize_to (format : property list -> string) =
  23. format [ ("name", String name); ("age", Int age) ]
  24.  
  25. end
  26.  
  27.  
  28. (* implements (property list -> string) interface / depends on it *)
  29. let properties_string properties =
  30. let value_string value = match value with
  31. | String s -> "\"" ^ s ^ "\""
  32. | Int i -> string_of_int i
  33. in
  34. let property_string (name, value) = name ^ " = " ^ (value_string value) in
  35. let concat_property str prop = str ^ " ; " ^ property_string prop in
  36. match properties with
  37. | [] -> "{}"
  38. | p::ps -> "{ " ^ List.fold_left concat_property (property_string p) ps ^ " }"
  39.  
  40. (* implements (property list -> string) interface / depends on it *)
  41. let json_object_string properties =
  42. let value_string value = match value with
  43. | String s -> "\"" ^ s ^ "\""
  44. | Int i -> string_of_int i
  45. in
  46. let property_string (name, value) = "\"" ^ name ^ "\": " ^ (value_string value) in
  47. let concat_property str prop = str ^ ", " ^ property_string prop in
  48. match properties with
  49. | [] -> "{}"
  50. | p::ps -> "{ " ^ List.fold_left concat_property (property_string p) ps ^ " }"
  51.  
  52. let example_b () =
  53. let p = new person_b "John Smith" 30 in
  54. Printf.printf "person_b : %s\n" (p#serialize_to properties_string) ;
  55. Printf.printf "person_b : %s\n" (p#serialize_to json_object_string)
  56.  
  57. let () =
  58. example_a () ;
  59. example_b ()
  60.  
Success #stdin #stdout 0s 4072KB
stdin
Standard input is empty
stdout
person_a : { name = "John Smith" ; age = 30 }
person_b : { name = "John Smith" ; age = 30 }
person_b : { "name": "John Smith", "age": 30 }