Ocaml Implementation

I'm trying to learn ocaml right now and wanted to start with a small program, generating all the bit combinations: ["0", "0", "0"] ["0", "0", "1"] ["0", " 1 "," 0 "] ... etc.

My idea is the following code:

let rec bitstr length list =
  if length = 0 then
    list
  else begin
    bitstr (length-1)("0"::list);
    bitstr (length-1)("1"::list);
  end;;

But I get the following error:

Warning S: this expression should have type unit.
val bitstr : int -> string list -> string list = <fun>
# bitstr 3 [];;
- : string list = ["1"; "1"; "1"]

I did not understand what to change, can you help me?

Regards Philipp

+5
source share
3 answers

begin foo; bar end foo , bar. , foo ocaml , foo , , (.. , ) - .

"0", . , . @:

let rec bitstr length list =
  if length = 0 then
    [list]
  else
    bitstr (length-1)("0"::list) @ bitstr (length-1)("1"::list);;

, length = 0 case return [list] list, .

+14

sepp2k , ( , , ):

let rec bitstr = function
   0 -> [[]]
 | n -> let f e = List.map (fun x -> e :: x) and l = bitstr (n-1) in 
        (f "0" l)@(f "1" l);;

, bitsr 2 [["0"; "0"]; ["0"; "1"]; ["1"; "0"]; ["1"; "1"]]. -, . , , ocaml.

+5

I like getting other ideas!

So here it is ...

let rec gen_x acc e1 e2 n = match n with
| 0 -> acc
| n -> (
  let l = List.map (fun x -> e1 :: x) acc in
  let r = List.map (fun x -> e2 :: x) acc in
  gen_x (l @ r) e1 e2 (n - 1)
);;

let rec gen_string = gen_x [[]] "0" "1"
let rec gen_int    = gen_x [[]]  0   1

gen_string 2
gen_int    2

Result:

[["0"; "0"]; ["0"; "1"]; ["1"; "0"]; ["1"; "1"]]

[[0; 0]; [0; 1]; [1; 0]; [1; 1]]
0
source

All Articles