Source

ocaml-logicm / tests.ml

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
open ExtStream
open LogicM_ops


module type Tests_sig
 =
  sig
    module LogicM
     :
      sig
        type 'a m
        val return : 'a -> 'a m
        val from_stream : 'a Stream.t -> 'a m
(*
        type 'a mplus_sig = 'a m -> 'a m -> 'a m
        val ( <+> ) : 'a mplus_sig
*)
        val ( <+> ) : 'a m -> 'a m -> 'a m
        val filter : ('a -> bool) -> 'a m -> 'a m
        val runL : int option -> 'a m -> 'a list
        val mzero : 'a m
        val ifm : 'a m -> th:('a m -> 'b) -> el:(unit -> 'b) -> 'b
        val ifteu : 'a m -> ('a -> 'b m) -> (unit -> 'b m) -> 'b m
        val guard : bool -> unit m

        val destruct_bind : 'a m -> ('a -> 'a m -> 'b m) -> 'b m -> 'b m
        val destruct_bindu : 'a m -> ('a -> 'a m -> 'b m) -> (unit -> 'b m) -> 'b m

        val once : 'a m -> 'a m

        val impl_name : string
      end

    type bindr = { bind : 'a 'b .
      ('a -> 'b LogicM.m) -> 'a LogicM.m -> 'b LogicM.m
    }

    val run_test : time:((unit -> unit) -> unit -> unit) ->
      fn:string -> (bindr:bindr -> unit -> unit) -> unit

  end



module TestsF (T : Tests_sig)
 =
  struct

    open T
    open LogicM

(*
module Lz
 =
  struct

    type 'a partial_list = ('a list -> 'a list)

    let empty_partial_list : 'a partial_list =
    (fun x -> x)

    let cons : 'a -> 'a list -> 'a list = fun h t -> h :: t

    let append : 'a partial_list -> 'a -> 'a partial_list =
    fun prefix x ->
      (fun xs -> (prefix (cons x (xs))))

    let (to_list : 'a partial_list -> 'a list) =
    fun p ->
      let () = Printf.printf "to_list#1\n%!" in
      let pf = p in
      let () = Printf.printf "to_list#2\n%!" in
      pf []


    let to_list_take : int -> 'a partial_list -> 'a list =
fun _ _ -> raise Exit


    let nums =
      let rec loop lst i =
        if i = 20
        then lst
        else
          let () = Printf.printf "loop/i=%i %!" i in
          (* тут энергично строится список вызовами loop *)
          loop (append lst i) (i+1)
      in
        loop empty_partial_list 0


    let print_list lst =
      ( List.iter (Printf.printf "%i %!") lst;
        Printf.printf "\n%!"
      )

    let () = print_list (to_list (nums))

  end

let () = exit 0
*)



(* let point n = (Printf.printf "point %s... %!" n; ignore (read_line ())) *)

(*
let run_test_interleave () =
  Printf.printf "test_interleave: %!";
  let s_odds = Stream.ints ~nstep:2 1 in
(*
  let s_odds = Stream.map (fun x -> Printf.printf "odd: %i\n" x; x) s_odds in
*)
let () = point "before fromstream" in
  let odds = from_stream s_odds in
  let four = return 4 in
let () = point "before +" in
  let odds_and_four = odds <+> four in
(*
  let evens = filter (fun x -> x mod 2 = 0) odds_and_four in
*)
let () = point "before filter" in
  let evens = filter (fun x -> x mod 2 = 0) odds_and_four in
let () = point "before runL" in
  List.iter (Printf.printf "%i %!") (runL (Some 1) evens);
  print_newline ()


let () = run_test_interleave ()


let () = exit 0
*)



let test_interleave ~bindr () =
  ignore bindr;
  Printf.printf "test_interleave: %!";
  let odds : int LogicM.m = from_stream (Stream.ints ~nstep:2 1) in
  let four : int LogicM.m = return 4 in
  let odds_and_four = odds <+> four in
  let evens = filter (fun x -> x mod 2 = 0) odds_and_four in
  List.iter (Printf.printf "%i %!") (runL (Some 1) evens);
  print_newline ()



let test_bind ~bindr () =
  Random.init 12345678;
  let ( >>= ) m f = bindr.bind f m in
  let gen_randoms = Stream.from_repeat (fun () -> Random.int 10) ()
  and mkpair x y = (x, y)
  and gen_numbers : int Stream.t = Stream.ints 0 ~nend:10 in
  let gen_randoms_numbered = Stream.map2 mkpair gen_randoms gen_numbers in
  let gen_randoms_numbered = Stream.map
     (fun (n, ord) ->
(*
        Printf.printf "pre:ord=%i,n=%i\n%!" ord n;
*)
        (n, ord)
     )
     gen_randoms_numbered in
  let m1 = from_stream gen_randoms_numbered in
  let bindfunc (n, ord) =
    from_stream
      (Stream.map
         (fun m -> Printf.sprintf "d:ord=%i,n=%i,m=%i" ord n m)
         (Stream.ints ~nend:n 1)
      )
  in
  let m2 = m1 >>= bindfunc in
  List.iter (Printf.printf "r:%s\n%!") (runL (Some 1000) m2);
  print_newline ()


let step_colatz n : int m =
(*
  Printf.printf "c:%i %!" n;
*)
  if n = 1 then mzero else
  if n mod 2 = 0 then return & n/2 else
  let r = 3*n+1 in
    if r <= 0 then mzero else return r


let test_colatz1 nmax ~bindr () =
  let s = Stream.ints 1 ~nend:nmax in
  let m = from_stream s in
  let rec inner m : int m =
   ifm m ~th:(fun m -> inner (bindr.bind step_colatz m)) ~el:(fun () -> mzero)
  in
    ignore &
    runL (Some 1) &
    ifteu (inner m) (fun x -> Printf.printf "left value: %i\n" x; mzero)
      (fun () -> (*Printf.printf "colatz ok for ints <= %i\n" nmax;*) mzero)


let test_colatz2 nmax ~bindr () =
  let ( >>= ) m f = bindr.bind f m in
  let s = Stream.ints 1 ~nend:nmax in
  let m = from_stream s in
  let rec inner n : int m =
    step_colatz n >>= inner
  in
    ignore &
    runL (Some 1) &
    (m >>= inner >>= fun x -> Printf.printf "left value: %i\n" x; mzero)


let ( -- ) nfrom nto =
  assert (nfrom <= nto);
  from_stream (Stream.ints nfrom ~nend:nto)


module Su
 :
  sig
    val test : bindr:T.bindr -> unit -> unit
  end
 =
  struct
    type cell = { x : int; y : int; n : int }
    type board = cell list

    let xsize = 9
    let ysize = 9

(*
let () =
((  (0 -- (ysize-1) >>= fun q -> guard (q mod 3 = 0) >>= fun () -> return q)
   >>
  iter (fun q -> Printf.printf "%i \n" q)
)
; raise Exit
)
*)

    let lines_of_board b : string list =
      let a = Array.make_matrix ysize xsize '.' in
      let () =
        List.iter
          (fun {x=x; y=y; n=n} ->
             assert (a.(y).(x) = '.');
             a.(y).(x) <- Char.chr ((Char.code '0') + n)
          )
          b
      in
      a >> Array.map
        (fun line ->
           Array.fold_left
             (fun (str, i) c ->
                ( Printf.sprintf "%s%c %s" str c (if i = 2 then "  " else "")
                , (i+1) mod 3
                )
             )
             ("", 0)
             line
        ) >>
    Array.fold_left
      (fun (acc, i) (l, _) ->
         let acc = l :: acc in
         let acc = if i = 2 then "" :: acc else acc in
         (acc, (i+1) mod 3)
      )
      ([], 0)
   >> fst >> List.rev

    let print_board b =
      b >> lines_of_board >>
      List.iter (Printf.printf "%s\n");
      print_newline ()


(*
    module Ennum =
      struct
(*
        module H = Hashtbl.Make(struct type t = .... m let equal = (==) let hash _ = 0)
        open H
        let ht = create 7
        let find_opt m = try find ht m with 
*)
        let l = ref []
        let get_opt m = try Some (List.assq m !l) with Not_found -> None

        let get =
          let n = ref 0 in
          fun m ->
            match get_opt m with
            | None ->
                let c = !n in
                ( l := (m, c) :: !l;
                  incr n;
                  c
                )
            | Some c -> c

      end
*)


    let solve ~bindr board =
      let ( >>= ) m f = bindr.bind f m in
      let cell_is_empty x y =
        not & List.exists (fun {x=cx; y=cy} -> cx = x && cy = y) board
      in
      (0 -- (ysize-1) >>= fun y ->
       0 -- (xsize-1) >>= fun x ->
       guard (cell_is_empty x y) >>= fun () -> return (x, y)
      ) >>
      fun empty_cells ->
      let rec inner depth board empty_cells =
(*
let () = Printf.printf "depth=%i, ec#=%i   %!" depth (Ennum.get empty_cells) in
*)
        destruct_bindu empty_cells
          (fun (x, y) empty_cells ->
(*
let () = Printf.printf "empty cell: (%i, %i)\n%!" x y in
*)
             1 -- 9 >>= fun n ->
             guard (not & List.exists
               (fun {x=cx; y=cy; n=cn} ->
                  (n = cn) &&
                  ((x = cx) || (y = cy) || (x/3 = cx/3 && y/3 = cy/3))
               ) board) >>= fun () ->
(*
let () = Printf.printf "cont with (%i, %i) := %i\n%!" x y n in
*)
               inner (depth+1) ({x=x; y=y; n=n} :: board) empty_cells
          )
          (fun () ->
(*
let () = Printf.printf "solution found!\n%!" in
*)
             return board)
      in
        inner 0 board empty_cells


    let example_txt =
        ".9..1.3.26.1.......2.8...91..8.....74"
      ^ "....8..3....3185.9....2.....2..5.493.549..2."

    let board_of_txt txt =
      assert (String.length txt = xsize * ysize);
      let cellch ch =
        match ch with
        | '.' -> None
        | '1'..'9' -> Some ((Char.code ch) - (Char.code '0'))
        | _ -> assert false in
      let r = ref [] in
      ( for y = 0 to ysize-1 do
          for x = 0 to xsize-1 do
            match (cellch txt.[xsize*y + x]) with
            | None -> ()
            | Some n -> r := {x=x; y=y; n=n} :: !r
          done
        done
      ; !r
      )

    let example : board = board_of_txt example_txt

    let test ~bindr () =
      print_board example;
      runL None (once (solve ~bindr example)) >>
      let c = ref 0 in
      List.iter (fun board ->
         incr c; Printf.printf "sol#%i\n%!" !c; print_board board
        )

  end


let time f x =
  let t_beg = Unix.gettimeofday () in
  let r = f x in
  let t_end = Unix.gettimeofday () in
  ( Printf.printf "time = %.2f\n%!" (t_end -. t_beg)
  ; r
  )


let __test1 ~bindr () =
  let () = ignore bindr in
  1 -- 2 >> fun m ->
  let th_pr h _t = (Printf.printf "h=%i\n%!" h; mzero)
  and el_pr () = (Printf.printf "fin\n%!"; return ()) in
  ( ( (destruct_bindu m th_pr el_pr) <+>
      (destruct_bindu m th_pr el_pr) <+>
      (destruct_bindu m th_pr el_pr) <+>
      (destruct_bindu m th_pr el_pr) <+>
      (destruct_bindu m th_pr el_pr)
    ) >>
    runL None >> ignore
  )


let _test1 ~bindr () =
  let ( >>= ) m f = bindr.bind f m in
  let _map f m = m >>= fun x -> return (f x) in
  let rec inner acc m =
    destruct_bind m
      (fun x m ->
         guard (0 = x land (x-1)) >>= fun () ->
         inner (x::acc) m
      )
      (return acc)
(*
    if n = 1 then return a else
    guard (n mod 2 = 0) >>= fun () ->
    inner (n/2, a*2)
*)
  in
    let r = (1 -- 100) >> inner [] in
    let l = runL None r in
    List.iter (fun q -> List.iter (Printf.printf "%i %!") q; print_newline ()) l;
    print_newline ()



let run_tests () =
  let run_test = run_test ~time in
  (
    Printf.printf "====== STARTED TESTING LogicM_%s ======\n%!"
      LogicM.impl_name;

    run_test ~fn:"interleave" test_interleave;
    run_test ~fn:"bind" test_bind;
    run_test ~fn:"colatz1" (test_colatz1 30000);
    run_test ~fn:"colatz2" (test_colatz2 30000);
    run_test ~fn:"sudoku" Su.test;

    Printf.printf "====== FINISHED TESTING LogicM_%s ======\n%!"
      LogicM.impl_name;
  )


end


module T_stream = TestsF(Tests_stream)

module T_cps = TestsF(Tests_cps)

module T_list = TestsF(Tests_list)


let () =
  (
    T_stream.run_tests ();
    T_cps.run_tests ();
    T_list.run_tests ();
  )