xavierm02

Untitled

Nov 12th, 2012
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.14 KB | None | 0 0
  1. let l = [ 0; 1; 3; -1; -2; -4; 10 ];;
  2.  
  3. let rec remove_negative = function
  4.     | [ ] -> [ ]
  5.     | head :: tail ->
  6.         if head < 0 then
  7.             remove_negative tail
  8.         else
  9.             head :: remove_negative tail
  10. ;;
  11.  
  12. (* And here is the function I would like to be able to write: *)
  13. let rec remove_negative l = match l with
  14.     | [ ] -> [ ]
  15.     | head :: tail ->
  16.         if head < 0 then
  17.             (* remove all the items at the beginning that are negative *)
  18.             remove_negative tail
  19.         else
  20.             (* when you get one non-negative item *)
  21.             let loop prev curr = match curr with
  22.                 | [ ] -> l
  23.                 | head :: tail ->
  24.                     (* make the list "skip" all items that are negative *)
  25.                     if head < 0 then
  26.                         prev.tail <- tail
  27.                     else ( );
  28.                     loop prev tail
  29.             in
  30.             loop l tail
  31. (* *)
  32.  
  33. let rec print_list = function
  34.     | [ ] -> ( )
  35.     | head :: tail ->
  36.         print_int head;
  37.         print_newline ( );
  38.         print_list tail
  39. ;;
  40.  
  41. print_list( remove_negative l );;
Advertisement
Add Comment
Please, Sign In to add comment