Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ocaml recursive pattern matching

Tags:

matching

ocaml

I'm trying to write a simple recursive function that look over list and return a pair of integer. This is easy to write in c/c++/java but i'm new to ocaml so somehow hard to find out the solution due to type conflict

it should goes like ..

let rec test p l = ... ;;
val separate : (’a -> bool) -> ’a list -> int * int = <fun>
test (fun x -> x mod 2 = 0) [-3; 5; 2; -6];; 
- : int * int = (2, 2)

so the problem is how can i recursively return value on tuple ..

like image 479
REALFREE Avatar asked Jun 15 '10 04:06

REALFREE


1 Answers

One problem here is that you are returning two different types: an int for an empty list, or a tuple otherwise. It needs to be one or the other.

Another problem is that you are trying to add 1 to test, but test is a function, not a value. You need to call test on something else for it to return a value, but even then it is supposed to return a tuple, which you can't add to an integer.

I can't figure out what you want the code to do, but if you update your question with that info I can help more.

One guess that I have is that you want to count the positive numbers in the list, in which case you could write it like this:

let rec test l = 
    match l with [] -> 0
   | x::xs -> if x > 0 then 1 + (test xs)
              else test xs;;

Update: since you've edited to clarify the problem, modify the above code as follows:

let test l =
  let rec test_helper l pos nonpos = 
    match l with [] -> (pos, nonpos)
   | x::xs -> if x > 0 then test_helper xs 1+pos, nonpos
              else test_helper xs pos 1+nonpos
  in test_helper l 0 0;;

Using the accumulators help a lot in this case. It also makes the function tail-recursive which is always good practice.

like image 168
danben Avatar answered Sep 23 '22 10:09

danben