Commits

camlspotter  committed 1f64312

aded examples

  • Participants
  • Parent commits f8a7d89
  • Branches gcaml

Comments (0)

Files changed (2)

File dcamlexamples/ex030_monad.ml

     }
 end
 
+module List = struct
+  let t = 
+    { Monad.return = (fun x -> [x]);
+      bind = (fun v f -> List.flatten (List.map f v)) }
+end
+
 module Overloaded : sig
   type ('a, 'am, 'bm) t
   val return : $:('a, 'am, 'bm) t -> 'a -> 'am
   val bind : $:('a, 'am, 'bm) t -> 'am -> ('a -> 'bm) -> 'bm
   val option : ('a, 'a option, 'b option) t
+  val list : ('a, 'a list, 'b list) t
 end = struct
   include Monad
   let option = Option.t
+  let list = List.t
 end
 
 open Overloaded
 
 let _ = 
-  assert (bind (return 1) (fun x -> Some (float x)) = Some 1.0)
+  assert (bind (return 1) (fun x -> Some (float x)) = Some 1.0);
+  assert (bind (return 1) (fun x -> [float x; float (x+1)]) = [1.0; 2.0]);
 ;;
 

File dcamlexamples/ex040_show.ml

+module Show_class = struct
+  type 'a t = 'a -> string
+  let show $:t = t
+end
+
+module Int = struct
+  let t = string_of_int
+end
+
+module Float = struct
+  let t = string_of_float
+end
+
+module Char = struct
+  let t = String.make 1 
+end
+
+module String = struct
+  let t x = x
+end
+
+module Bool = struct
+  let t = string_of_bool
+end
+
+module Tuple2 = struct
+  let t (x,y) = 
+    "("
+    ^ Show_class.show x
+    ^ ","
+    ^ Show_class.show y
+    ^ ")"
+end
+
+module List = struct
+  let t l = 
+    let rec t = function
+      | [] -> ""
+      | [x] -> Show_class.show x
+      | x::xs -> 
+          Show_class.show x 
+          ^ ";"
+          ^ t xs
+    in
+    "[" ^ t l ^ "]"
+end
+
+module Show : sig
+  type 'a t
+  val show : $:'a t -> 'a -> string
+
+  val int : int t
+  val float : float t
+  val char : char t
+  val string : string t
+  val bool : bool t
+  val tuple2 : $:'a t -> $:'b t -> ('a * 'b) t
+  val list : $:'a t -> 'a list t
+end = struct
+  include Show_class
+  let int = Int.t
+  let float = Float.t
+  let string = String.t
+  let char = Char.t
+  let bool = Bool.t
+  let tuple2 = Tuple2.t
+  let list = List.t
+end
+
+open Show
+
+let _ =
+  assert (
+    show [("hello", "world");
+          ("bye", "universe")]
+      = "[(hello,world);(bye,universe)]"
+  )
+