Skip to content

Instantly share code, notes, and snippets.

@kig
Created December 14, 2008 14:23
Show Gist options
  • Save kig/35696 to your computer and use it in GitHub Desktop.
Save kig/35696 to your computer and use it in GitHub Desktop.
open Prelude
type 'a accum = Acc of 'a | Done of 'a
let optMap f x = match x with None -> None | Some y -> Some (f y)
let string_of_char c = String.make 1 c
let (^.) s c = s ^ string_of_char c
module Stream =
struct
include Stream
let nextOpt st =
match peek st with
| None -> None
| x -> (junk st; x)
let rec foldlBreak f init st =
match nextOpt st with
| None -> init
| Some x ->
begin match f init x with
| Acc a -> foldlBreak f a st
| Done b -> b
end
let rec foldl f init st = foldlBreak (fun s i -> Acc (f s i)) init st
let map f st = from (fun _ -> optMap f (nextOpt st))
let remap f init st =
from (fun _ ->
match peek st with
| None -> None
| Some x -> Some (foldlBreak f init st))
let join s st = from (fun i -> if i mod 2 = 0 then nextOpt st else Some s)
end
let lines =
Stream.remap (fun s c -> if c = '\n' then Done s else Acc (s ^. c)) ""
let () =
withFiles (fun ic oc ->
let s = Stream.of_channel ic in
let rev_lines = Stream.map srev (lines s) in
Stream.iter (output_string oc) (Stream.join "\n" rev_lines)
) "src" "dst"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment