Reputation: 1426
I'm learning ocaml and I'm trying to write easy function which prints out firsts given as argument int's.
What I have wrote:
let rec take(number, lista)=
let rec take_acc(number, lista, acc)=
match number with
| 0 -> []
| number < 0 -> []
| number > lista.length -> lista
| number < lista.length -> take_acc(number-1, lista.tl, [email protected]);;
take_acc(number, lista, [])
let listas = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: [];;
take(2,listas);;
The point is, that given code above gives me error:
Error: Unbound value take
What I'm doing wrong?
The point is that this code works:
let xxl = 11 :: 33 :: 54 :: 74 :: [];;
let rec take2 (ile,xxx) =
if ile=0 || ile<0 then []
else
if ile>(List.length xxl) then take2(ile-1,xxx)
else
List.hd xxx :: take2(ile-1,List.tl xxx);;
Where is difference beetwen these two programs?
EDIT: Due to Jeffrey Scofield's suggestion I have written something like this:
let rec take2(ilosc, lista) =
let rec take_acc(ilosc, lista, acc) =
if ilosc = 0 || ilosc < 0 then []
else
if ilosc > List.length lista
then lista
else
take_acc(ilosc-1, lista.tl, [email protected]);;
let listas = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: [];;
take2(2,listas);;
Still the same.
Upvotes: 0
Views: 2067
Reputation: 66818
Your code is not syntactically well formed. So it couldn't ever reach the point of saying that take isn't defined.
The first thing to fix is your use of patterns. The construct number < 0
isn't a pattern, it's a boolean expression. You can have a boolean as part of a pattern using when
:
| _ when number < 0
However, this isn't particulary good style for what you want to test. It might be better just to use if
for your tests.
The next thing to fix might be your use of lista.length
. The way to get the length of a list in OCaml is List.length lista
.
Upvotes: 2