The Computer Language
Benchmarks Game

regex-dna OCaml #2 program

source code

(* The Computer Language Benchmarks Game
 * Contributed by Christophe TROESTLER

open Printf

let variants = ["agggtaaa\\|tttaccct";          "[cgt]gggtaaa\\|tttaccc[acg]";
                "a[act]ggtaaa\\|tttacc[agt]t";  "ag[act]gtaaa\\|tttac[agt]ct";
                "agg[act]taaa\\|ttta[agt]cct";  "aggg[acg]aaa\\|ttt[cgt]ccct";
                "agggt[cgt]aa\\|tt[acg]accct";  "agggta[cgt]a\\|t[acg]taccct";

(* Remove the "\\" which is mandatory in OCaml regex. *)
let re_bs = Str.regexp_string "\\"
let to_string = Str.global_replace re_bs ""

let subst = ["B", "(c|g|t)"; "D", "(a|g|t)";   "H", "(a|c|t)"; "K", "(g|t)";
             "M", "(a|c)";   "N", "(a|c|g|t)"; "R", "(a|g)";   "S", "(c|g)";
             "V", "(a|c|g)"; "W", "(a|t)";     "Y", "(c|t)"]

(* Read all of a redirected FASTA format file from stdin. *)
let file_data, file_length =
  let b = Buffer.create 0xFFFF and s = String.create 0xFFF and r = ref 1 in
  while !r > 0 do
    r := input stdin s 0 0xFFF;   Buffer.add_substring b s 0 !r
  Buffer.contents b, Buffer.length b

(* Remove FASTA sequence descriptions and all linefeed characters.  *)
let dna = Str.global_replace (Str.regexp "^>.*$\\|\n") "" file_data
let code_length = String.length dna

(* Count matches of [re]. *)
let count re s =
  let re = Str.regexp_case_fold re and i = ref 0 and n = ref 0 in
    while true do i := 1 + Str.search_forward re s !i; incr n done; assert false
  with Not_found -> !n

let () =
  List.iter (fun re -> printf "%s %i\n" (to_string re) (count re dna)) variants;
  let b = ref dna in
  List.iter (fun (re, s) ->
               b := Str.global_replace (Str.regexp_case_fold re) s !b) subst;
  printf "\n%i\n%i\n%i\n" file_length code_length (String.length !b)

notes, command-line, and program output

32-bit Ubuntu one core
The OCaml native-code compiler, version 4.03.0

Tue, 26 Apr 2016 02:02:00 GMT

mv regexdna.ocaml-2.ocaml
/usr/local/bin/ocamlopt -noassert -unsafe -nodynlink -inline 100 unix.cmxa str.cmxa -o regexdna.ocaml-2.ocaml_run
File "", line 25, characters 39-52:
Warning 3: deprecated: String.create
Use Bytes.create instead.
0.44s to complete and log all make actions

./regexdna.ocaml-2.ocaml_run 0 < regexdna-input5000000.txt



Fatal error: exception Failure("Buffer.add: cannot grow buffer")