Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml introduction

Tags:

ocaml

i'm trying to learn ocaml right now and wanted to start with a little program, generating all bit-combinations:

["0","0","0"]
["0","0","1"]
["0","1","0"]

... and so on

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?

Best regards Philipp

like image 652
Philipp Andre Avatar asked May 10 '10 13:05

Philipp Andre


1 Answers

begin foo; bar end executes foo and throws the result away, then it executes bar. Since this makes only sense if foo has side-effects and no meaningful return value ocaml emits a warning if foo has a return value other than unit, since everything else is likely to be a programmer error (i.e. the programmer does not actually intend for the result to be discarded) - as is the case here.

In this case it really does make no sense to calculate the list with "0" and then throw it away. Presumably you want to concatenate the two lists instead. You can do this using the @ operator:

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

Note that I also made the length = 0 case return [list] instead of just list so the result is a list of lists instead of a flat list.

like image 114
sepp2k Avatar answered Nov 25 '22 21:11

sepp2k