Re: last item. no output

"John Whitington [email protected] [ocaml_beginners]" <[email protected]>
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <[email protected]>
Hi,

Roelof Wobben [email protected] [ocaml_beginners] wrote:
> Matthieu Dubuget [email protected] [ocaml_beginners] schreef op
> 18-10-2014 17:44:
>>
>>
>> Le 18/10/2014 17:38, Roelof Wobben [email protected] [ocaml_beginners] a
>> écrit :
>> > Almost but without the () and your script gives a error message.
>>
>> A good exercise would be:
>> - to correct it
>> - and to explain what it is supposed to do?
>>
>> If you want help, please ask more precise questions. The benefit of it
>> will be that most of the time, you'll find the answer yourself while
>> writing the question.
>>
>> Before your write your functions, try to write it's type: it will help a
>> lot.
>>
>> Hoping this will help
>>
>> --
>> Matthieu Dubuget
>> Guide d’autodéfense numérique : http://guide.boum.org
>>
>>
>
> oke,
> After some trail and error this seems to work :
>
> let rec last list =
>     match list with
>     | [] -> None
>     | [x] -> None
>     | [x;y]-> Some (x,y)
>     | hd :: tl  -> last tl
>     ;;

Three little points:

a) It's best not to use the names of types (like 'list') for argument 
names - just use 'l' or some other name. You've also used the names 'hd' 
an 'tl', which are the names of some functions in the List module of the 
standard library. This isn't wrong, just not great style.

b) You can combine some of your cases, if the right hand sides are the 
same, and you can use an underscore when a name is not used, so that the 
person reading the code knows that a name isn't used:

let rec last l =
   match l with
   | [] | [_] -> None
   | [x; y] -> Some (x, y)
   | _::t -> last t

In fact, if you like, you can get rid of 'l' as well, since you 
introduce it and match on it immediately:

let rec last = function
   | [] | [_] -> None
   | [x; y] -> Some (x, y)
   | _::t -> last t

But you might want to avoid this construction until you're more advanced 
-- it's idiomatic, but not really intuitive.

Thanks,

-- 
John Whitington
Director, Coherent Graphics Ltd
http://www.coherentpdf.com/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.