Sha256: 21a976a638ae080e382d3014d44ffadc145f3db6050200e0b936e8bbb60176aa

Contents?: true

Size: 979 Bytes

Versions: 68

Compression:

Stored size: 979 Bytes

Contents

open Base

let (>|>) f g x = g (f x)

let repeat n ch = 
  Array.init n ~f:(fun _ -> ch) 
  |> Array.to_list
  |> String.of_char_list

let collapse = function
| [] -> failwith "empty string not expected here"
| [x] -> Char.to_string x
| (x::_) as g -> Printf.sprintf "%d%c" (List.length g) x

let to_int = String.of_char_list >|> Int.of_string

let decode_to_tuple (s: 'a list): ((int * 'a) * 'a list) = 
  match List.split_while ~f:Char.is_digit s with
  | ([], (x::xs)) -> ((1, x), xs)
  | (ds, (x::xs)) -> let count = to_int ds in ((count, x), xs)
  | _ -> failwith "case not expected"

let encode =
  String.to_list
  >|> List.group ~break:(Char.(<>))
  >|> List.map ~f:collapse
  >|> String.concat ~sep:""

let decode = 
  let rec go acc input =
    if List.is_empty input then acc
    else let (t, rest) = decode_to_tuple input in go (t :: acc) rest in
  String.to_list
  >|> go []
  >|> List.rev
  >|> List.map ~f:(fun (cnt, c) -> repeat cnt c)
  >|> String.concat ~sep:""

Version data entries

68 entries across 68 versions & 1 rubygems

Version Path
trackler-2.2.1.159 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.158 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.157 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.156 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.155 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.154 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.153 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.152 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.151 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.150 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.149 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.148 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.147 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.146 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.145 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.144 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.143 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.142 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.141 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.140 tracks/ocaml/exercises/run-length-encoding/example.ml