Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Some/None
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Max Skaller <skaller@o...>
Subject: Re: [Caml-list] Some/None
Oliver Bandel wrote:

>Does it make sense to give back None/Some
>out of a function 
>
Oh yes! I do this all the time, lots and lots.

Consider

let lst = [1;2;3;4]
let pos lst x =
  let pos lst n = match lst with
    | h :: t ->
      if h = x
      then Some n
      else pos t (n+1)
    | [] -> None
   in
    pos lst 0

which searches a list for a number x,
and returns its position n as 

  Some n 

if it is found in the list, or

  None

if it isn't: its position in the list is None,
it doesn'tr have a position, or Some position
if it does.

>(e.g. is_regularfile/is_directory/...)
>

What you want here is:

    type file_type_t = Regular | Directory | Special | Root | NonExistant

   let file_type (s:string): file_type_t =

    (code to find the file type here) ...

This function finds the type of the file and returns it,
I include the case the file is non-existant.

This is exactly a C enumeration. Only you can have
arguments. For example, an extended file function might
use the construction

    type file_data =
      | Regular of int (* file size in megs *)
      | Directory of int (* number of entries *)
      | Special
    ....

This is a union of cases, just like an enumeration,
only now some extra data is tacked on to some
of the cases.


-- 
John Max Skaller, mailto:skaller@ozemail.com.au
snail:10/1 Toxteth Rd, Glebe, NSW 2037, Australia.
voice:61-2-9660-0850




-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners