Sha256: 46256ce4fea20c1b85f600f1ae084d9f7a61c288049f9b5664f6dc5be07e7497

Contents?: true

Size: 967 Bytes

Versions: 151

Compression:

Stored size: 967 Bytes

Contents

open Core

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 -> 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:((<>))
  >|> 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

151 entries across 151 versions & 1 rubygems

Version Path
trackler-2.2.1.110 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.109 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.108 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.107 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.106 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.105 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.104 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.103 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.102 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.101 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.100 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.99 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.98 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.97 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.96 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.95 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.94 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.93 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.92 tracks/ocaml/exercises/run-length-encoding/example.ml
trackler-2.2.1.91 tracks/ocaml/exercises/run-length-encoding/example.ml