Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml - Generate list of all char values

Tags:

ocaml

I have been trying to find a simple way to get a list of all possible char values (i.e. ['\000';'\001';...;'\255']) in OCaml.

In Python I'd do a simple list comprehension like:

[chr(x) for x in range(255)]

However, the way I currently know in OCaml is much less simple:

all_chrs = let rec up_to = fun lst max -> 
  match lst with
  | [] -> failwith "Invalid_input"
  | hd::tl ->
    let up = hd + 1 in
    if up = max then up::lst
    else up_to (up::lst) max
in let all_ascii = up_to [0] 255
in List.map Char.chr all_ascii

Can anyone point me to the simplest way to do this?

Thanks!

like image 392
James Allingham Avatar asked Apr 21 '18 14:04

James Allingham


1 Answers

With OCaml 4.06, using List.init, you can do it pretty easily:

let l = List.init 256 Char.chr

On older versions of OCaml, you'll need a bit more code:

let l =
 let rec aux i acc =
  if i < 0 then acc else aux (i-1) (Char.chr i::acc)
 in aux 255 []

Update: from Martin Jambon's comment:

let l = Array.to_list (Array.init 256 Char.chr)
like image 95
PatJ Avatar answered Nov 28 '22 22:11

PatJ