Reputation: 1
I have to make a function that takes list a list and returns list of pairs of first and last element,2nd and 2nd last and so forth It doesn't matter if the list has even or odd number of elements because if its odd i will just ignore the middle element.The idea i have is that make a new rec fun that takes old list and its revers as input i think i finished the code but i get Syntax error for ;;
let lip l =
if [] then []
else let l1=l l2=List.rev l in
let rec lp l1 l2 = match l1,l2 with
| [],[] ->[]
| [],h2::t2->[]
| h1::_,h2::_ ->
if (List.length l -2) >= 0 then [(h1,h2)]@ lp(List.tl l1) t2
else [] ;;
Upvotes: 0
Views: 1075
Reputation: 4998
The following code should at least compile:
let lip list1 =
if list1 = [] then []
else
let list2=List.rev list1 in
let rec lp l1 l2 = match l1,l2 with
| [], [] ->[]
| [], _::_->[]
| h1::_::_, h2::t2 -> (* l1 length >= 2*)
(h1,h2) :: lp(List.tl l1) t2
| h1::_,h2::t2 -> (* l1 length = 1 *)
[]
in
[]
I have made the following changes:
lip
to make clear they are different from the arguments of lp
let l1 = l
| [h1, _] -> ...
lp
needs to be followed with the actual body of lip
- to make it compile, we just return []
at the moment but you probably would like something else thereAs @Jeffrey Scofield already mentioned, you are not using lp
in your code. It could help if you added a comment that explains what you'd like to achieve and what the intended role of lp
is.
Upvotes: 0
Reputation: 66823
There are quite a few errors in your code.
I think the specific error you're seeing is caused by the fact that there is no in
after let rec lp ...
.
Every let
that's not at the top level of a module needs to be followed by in
. One way to think of it is that it's a way of declaring a local variable for use in the expression that appears after in
. But you need to have the in expr
.
Another way to look at it is that you're defining a function named lp
but you're not calling it anywhere.
As @lambda.xy.x points out, you can't say if [] then ...
because []
isn't of type bool
. And you can't say let x = e1 y = e2 in ...
. The correct form for this is let x = e1 in let y = e2 in ...
(Or you can write let x, y = e1, e2 in ...
, which looks nicer for defining two similar variables to two similar values.)
Upvotes: 1