(*---------------------------------------------------------------------------*
  IMPLEMENTATION  cf_seq.ml

  Copyright (c) 2002-2006, James H. Woodyatt
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  OF THE POSSIBILITY OF SUCH DAMAGE. 
 *---------------------------------------------------------------------------*)

type 'a t = 'a cell Lazy.t and 'a cell = P of 'a * 'a t | Z

exception Empty

let nil = Lazy.lazy_from_val Z

let head s =
    match Lazy.force s with
    | P (hd, _) -> hd
    | Z -> raise Empty

let tail s =
    match Lazy.force s with
    | P (_, tl) -> tl
    | Z -> raise Empty

let rec concat s1 s2 =
    lazy begin
        match Lazy.force s1 with
        | P (hd, tl) -> P (hd, concat tl s2)
        | Z -> Lazy.force s2
    end

let rec flatten z =
    lazy begin
        match Lazy.force z with
        | Z -> Z
        | P (hd, tl) ->
            match Lazy.force hd with
            | P (hd2, tl2) -> P (hd2, flatten (lazy (P (tl2, tl))))
            | Z -> Lazy.force (flatten tl)
    end

let limit =
    let rec loop ?x n s =
        match Lazy.force s with
        | Z -> Z
        | P (hd, tl) when n > 0 -> P (hd, lazy (loop (pred n) tl))
        | _ ->
            match x with
            | None -> Z
            | Some x -> raise x
    in
    fun ?x n s ->
        if n < 0 then invalid_arg "Cf_seq.limit: n < 0";
        lazy (loop ?x n s)

let shift =
    let rec loop n = function
        | P (_, tl) when n > 0 -> loop (pred n) (Lazy.force tl)
        | cell -> cell
    in
    fun n s ->
        if n < 0 then invalid_arg "Cf_seq.shift: n < 0";
        lazy (loop n (Lazy.force s))

let rec sentinel x z =
    lazy begin
        match Lazy.force z with
        | Z -> raise x
        | P (hd, tl) -> P (hd, sentinel x tl)
    end

let reverse =
    let rec loop stack = function
        | P (hd, tl) -> loop (hd :: stack) (Lazy.force tl)
        | Z -> stack
    in
    fun s ->
        loop [] (Lazy.force s)

let length =
    let rec loop n = function
        | P (_, y) -> loop (succ n) (Lazy.force y)
        | Z -> n
    in
    fun s ->
        loop 0 (Lazy.force s)

let rec unfold f x =
    lazy begin
        match f x with
        | Some (y, x) -> P (y, unfold f x)
        | None -> Z
    end

let rec unfold2 f x =
    lazy begin
        match f x with
        | Some (_, x as y) -> P (y, unfold2 f x)
        | None -> Z
    end

let rec iterate f s =
    match Lazy.force s with
    | P (hd, tl) -> f hd; iterate f tl
    | Z -> ()

let rec predicate f s =
    match Lazy.force s with
    | P (hd, tl) -> f hd && predicate f tl
    | Z -> true

let rec constrain f s =
    lazy begin
        match Lazy.force s with
        | P (hd, tl) when f hd -> P (hd, constrain f tl)
        | _ -> Z
    end

let search f =
    let rec loop n s =
        match Lazy.force s with
        | P (hd, tl) -> if f hd then n else loop (succ n) tl
        | Z -> n
    in
    fun s ->
        loop 0 s

let rec fold f m s =
    match Lazy.force s with
    | P (hd, tl) -> fold f (f m hd) tl
    | Z -> m

let filter =
    let rec loop f s =
        match Lazy.force s with
        | P (hd, tl) when f hd -> P (hd, lazy (loop f tl))
        | P (_, tl) -> loop f tl
        | Z -> Z
    in
    fun f s ->
        lazy (loop f s)

let rec map f s =
    lazy begin
        match Lazy.force s with
        | P (hd, tl) -> P (f hd, map f tl)
        | Z -> Z
    end

let optmap =
    let rec loop f s =
        match Lazy.force s with
        | Z -> Z
        | P (hd, tl) ->
            match f hd with
            | Some y -> P (y, lazy (loop f tl))
            | None -> loop f tl
    in
    fun f s ->
        lazy (loop f s)

let listmap =
    let rec inner f cont = function
        | hd :: tl -> P (hd, lazy (inner f cont tl))
        | [] -> outer f cont
    and outer f s =
        match Lazy.force s with
        | P (hd, tl) -> inner f tl (f hd)
        | Z -> Z
    in
    fun f s ->
        lazy (outer f s)

let seqmap =
    let rec inner f cont s =
        match Lazy.force s with
        | P (hd, tl) -> P (hd, lazy (inner f cont tl))
        | Z -> outer f cont
    and outer f s =
        match Lazy.force s with
        | P (hd, tl) -> inner f tl (f hd)
        | Z -> Z
    in
    fun f s ->
        lazy (outer f s)

let partition f s = filter f s, filter (fun x -> not (f x)) s

let rec fcmp f s0 s1 =
    match Lazy.force s0, Lazy.force s1 with
    | P (hd1, tl1), P (hd2, tl2) ->
        let d = f hd1 hd2 in
        if d <> 0 then d else fcmp f tl1 tl2
    | P _, Z -> 1
    | Z, P _ -> -1
    | Z, Z -> 0

let cmp s0 s1 = fcmp Pervasives.compare s0 s1

let equal s0 s1 = cmp s0 s1 = 0

let rec first s =
    lazy begin
        match Lazy.force s with
        | P ((hd, _), tl) -> P (hd, first tl)
        | Z -> Z
    end

let rec second s =
    lazy begin
        match Lazy.force s with
        | P ((_, hd), tl) -> P (hd, second tl)
        | Z -> Z
    end

let split s = first s, second s

let rec combine s0 s1 =
    lazy begin
        match Lazy.force s0, Lazy.force s1 with
        | P (hd1, tl1), P (hd2, tl2) -> P ((hd1, hd2), combine tl1 tl2)
        | _, _ -> Z
    end

let rec iterate2 f s0 s1 =
    match Lazy.force s0, Lazy.force s1 with
    | P (hd1, tl1), P (hd2, tl2) -> f hd1 hd2; iterate2 f tl1 tl2
    | _, _ -> ()

let rec predicate2 f s0 s1 =
    match Lazy.force s0, Lazy.force s1 with
    | P (hd1, tl1), P (hd2, tl2) -> f hd1 hd2 && predicate2 f tl1 tl2
    | Z, Z -> true
    | _, _ -> false

let rec constrain2 f s0 s1 =
    lazy begin
        match Lazy.force s0, Lazy.force s1 with
        | P (hd1, tl1), P (hd2, tl2) when f hd1 hd2 ->
            P ((hd1, hd2), constrain2 f tl1 tl2)
        | _, _ ->
            Z
    end

let rec fold2 f m s0 s1 =
    match Lazy.force s0, Lazy.force s1 with
    | P (hd1, tl1), P (hd2, tl2) -> fold2 f (f m hd1 hd2) tl1 tl2
    | _, _ -> m

let filter2 =
    let rec loop f s1 s2 =
        match Lazy.force s1, Lazy.force s2 with
        | P (hd1, tl1), P (hd2, tl2) when f hd1 hd2 ->
            P ((hd1, hd2), lazy (loop f tl1 tl2))
        | P (_, tl1), P (_, tl2) ->
            loop f tl1 tl2
        | _, _ ->
            Z
    in
    fun f s1 s2 ->
        lazy (loop f s1 s2)

let rec map2 f s1 s2 =
    lazy begin
        match Lazy.force s1, Lazy.force s2 with
        | P (hd1, tl1), P (hd2, tl2) -> P (f hd1 hd2, map2 f tl1 tl2)
        | _, _ -> Z
    end

let optmap2 =
    let rec loop f s1 s2 =
        match Lazy.force s1, Lazy.force s2 with
        | P (hd1, tl1), P (hd2, tl2) ->
            begin
                match f hd1 hd2 with
                | Some y -> P (y, lazy (loop f tl1 tl2))
                | None -> loop f tl1 tl2
            end
        | _, _ ->
            Z
    in
    fun f s1 s2 ->
        lazy (loop f s1 s2)

let listmap2 =
    let rec inner f c1 c2 = function
        | hd :: tl -> P (hd, lazy (inner f c1 c2 tl))
        | [] -> outer f c1 c2
    and outer f s1 s2 =
        match Lazy.force s1, Lazy.force s2 with
        | P (hd1, tl1), P (hd2, tl2) -> inner f tl1 tl2 (f hd1 hd2)
        | _, _ -> Z
    in
    fun f s1 s2 ->
        lazy (outer f s1 s2)

let seqmap2 =
    let rec inner f c1 c2 s =
        match Lazy.force s with
        | P (hd, tl) -> P (hd, lazy (inner f c1 c2 tl))
        | Z -> outer f c1 c2
    and outer f s1 s2 =
        match Lazy.force s1, Lazy.force s2 with
        | P (hd1, tl1), P (hd2, tl2) -> inner f tl1 tl2 (f hd1 hd2)
        | _, _ -> Z
    in
    fun f s1 s2 ->
        lazy (outer f s1 s2)

let rec of_channel c =
    lazy (try P (input_char c, of_channel c) with End_of_file -> Z)

let of_substring s =
    let len = String.length s in
    let rec loop pos =
        let pos = succ pos in
        if pos < len then P (String.unsafe_get s pos, lazy (loop pos)) else Z
    in
    fun pos ->
        lazy (loop (pred pos))

let of_string s = of_substring s 0

let of_subarray a =
    let len = Array.length a in
    let rec loop pos =
        let pos = succ pos in
        if pos < len then P (Array.unsafe_get a pos, lazy (loop pos)) else Z
    in
    fun pos ->
        lazy (loop (pred pos))

let of_array a = of_subarray a 0

let rec of_function f = lazy (try P (f (), of_function f) with Not_found -> Z)

let rec of_list = function
    | [] -> Lazy.lazy_from_val Z
    | hd :: tl -> lazy (P (hd, of_list tl))

let rec to_channel s c =
    match Lazy.force s with
    | P (hd, tl) ->
        output_char c hd;
        to_channel tl c
    | Z ->
        ()

let to_string =
    let rec loop b = function
        | P (hd, tl) ->
            Buffer.add_char b hd;
            loop b (Lazy.force tl)
        | Z ->
            ()
    in
    fun s ->
        let b = Buffer.create 32 in
        loop b (Lazy.force s);
        Buffer.contents b

let to_substring =
    let rec loop str pos stop = function
        | P (hd, tl) when pos < stop ->
            String.unsafe_set str pos hd;
            loop str (succ pos) stop (Lazy.force tl)
        | x ->
            x
    in
    fun s str pos len ->
        if pos < 0 then
            invalid_arg "Cf_seq.to_substring: pos < 0";
        if pos + len > String.length str then
            invalid_arg "Cf_seq.to_substring: pos + len > String.length str";
        lazy (loop str pos len (Lazy.force s))

let to_array =
    let f cr _ =
        match !cr with
        | Z -> assert false
        | P (hd, tl) -> cr := Lazy.force tl; hd
    in
    fun s ->
        let len = length s in
        match Lazy.force s with
        | P _ as cell -> Array.init len (f (ref cell))
        | Z -> [| |]

let to_subarray =
    let rec loop v pos stop = function
        | P (hd, tl) when pos < stop ->
            Array.unsafe_set v pos hd;
            loop v (succ pos) stop (Lazy.force tl)
        | x ->
            x
    in
    fun s v pos len ->
        if pos < 0 then
            invalid_arg "Cf_seq.to_subarray: pos < 0";
        if pos + len > Array.length v then
            invalid_arg "Cf_seq.to_subarray: pos + len > Array.length v";
        lazy (loop v pos len (Lazy.force s))

let to_list s = List.rev (reverse s)

let rec to_buffer s b =
    match Lazy.force s with
    | P (hd, tl) ->
        Buffer.add_char b hd;
        to_buffer tl b
    | Z ->
        ()

let to_function s =
    let s0 = ref s in
    let rec loop () =
        match Lazy.force !s0 with
        | P (hd, tl) -> s0 := tl; hd
        | Z -> raise End_of_file
    in
    loop

let finishC_ _ = Lazy.lazy_from_val Z
let finishSC_ _ _ = Lazy.lazy_from_val Z

let writeC o f = lazy (P (o, f ()))
let evalC m = m finishC_

let writeSC o f s = lazy (P (o, f () s))
let evalSC m s = m finishSC_ s

module S = struct
    open Cf_smonad
    open Op
    
    let accumulate =
        let rec loop stack seq =
            match Lazy.force seq with
            | P (hd, tl) -> hd >>= fun x -> loop (x :: stack) tl
            | Z -> return (List.rev stack)
        in
        fun s -> loop [] s

    let rec sequence s =
        match Lazy.force s with
        | P (hd, tl) -> hd >>= fun _ -> sequence tl
        | Z -> return ()
end

module C = struct
    open Cf_cmonad
    open Op
    
    let accumulate =
        let rec loop stack seq =
            match Lazy.force seq with
            | P (hd, tl) -> hd >>= fun x -> loop (x :: stack) tl
            | Z -> return (List.rev stack)
        in
        fun s -> loop [] s

    let rec sequence s =
        match Lazy.force s with
        | P (hd, tl) -> hd >>= fun _ -> sequence tl
        | Z -> return ()
end

module SC = struct
    open Cf_scmonad
    open Op
    
    let accumulate =
        let rec loop stack seq =
            match Lazy.force seq with
            | P (hd, tl) -> hd >>= fun x -> loop (x :: stack) tl
            | Z -> return (List.rev stack)
        in
        fun s -> loop [] s

    let rec sequence s =
        match Lazy.force s with
        | P (hd, tl) -> hd >>= fun _ -> sequence tl
        | Z -> return ()
end

(*--- Snd of File [ cf_seq.ml ] ---*)
