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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With