Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignore function in OCaml

Tags:

ocaml

on page 95 of the book titled developing applications with objective caml

let imap f l =  
let l_res = icreate ()  
in while not (iempty l) do  
     ignore (icons (f (ihd l)) l_res) ;  
     ignore (itl l)
   done ;
   { l_res with c = List.rev l_res.c } ;;

What does the ignore function do in the above coding? I was able to get the same result without the ignore function implemented in the while loop as follows:

let imap f l =  
let l_res = icreate ()  
in while not (iempty l) do  
     (icons (f (ihd l)) l_res) ;  
     (itl l)
   done ;
   { l_res with c = List.rev l_res.c } ;;

Then the book goes on and says that The presence of ignore emphasizes the fact that it is not the result of the functions that counts here, but their side effects on their argument.

if the result of the functions does not count, then how does the while loop stop? In this case, it seems to me that the while loop will loop continuously if the result of (itl l) is ignored. Also, what side effects on their argument is the book refering to? Thank you

like image 383
ocamlNewcomer Avatar asked Dec 22 '10 07:12

ocamlNewcomer


1 Answers

Since the function itl mutates its input (in this case l), the while clause terminates when l is empty. I believe itl removes the first element of the list, so essentially you iterate over the elements of the list).

The calls to ignore are just for the readability: they signal to the reader that the functions are not used for their output -- so they must have some desired side effect.

EDIT: the call to ignore may also help eliminate compiler warnings (see the manual):

val ignore : 'a -> unit

Discard the value of its argument and return (). For instance, ignore(f x) discards the result of the side-effecting function f. It is equivalent to f x; (), except that the latter may generate a compiler warning; writing ignore(f x) instead avoids the warning.

like image 92
nimrodm Avatar answered Nov 05 '22 23:11

nimrodm