On 30 April 2014 07:49, Roelof Wobben <rwob...@hotmail.com> wrote:
>
>
> Op woensdag 30 april 2014 08:21:40 UTC+2 schreef James Reeves:
>
>>
>> 1. How do you find the last element of a seq with exactly one element?
>>
>
>    the last and the first element are the same
>

Right. So to formalise it:

    (defn last* [coll]
      (first coll))

I'm using "last*" as the name so that it doesn't conflict with the function
"last" in clojure.core.


2. How do you find out whether a seq has one element, or more than one
>> element?
>>
>
> Look at the length of the seq
>

Unlike vectors, seqs are simple structures and don't know their own length.

You can count seqs, but this involves iterating through every element in
turn. If all you want to do is find out whether there is more than one
element, there's a much simpler and more efficient way.


 3. How do you find out the last element if a seq with exactly two elements?
>>
>
> take the first element away and you have a seq of one element .
>

So in other words:

    (defn last* [coll]
      (first (rest coll)))


4. How do you find out the last element of a seq that may have one *or* two
>> elements?
>>
>
> Look at the length. If it has one element , see question 1
> if it has 2 elements, see question 3.
>

In code, this would be:

    (defn last* [coll]
      (if (more-than-one-element? coll)
        (first (rest coll))
        (first coll)))

The "more-than-one-element?" to be replaced with the answer to question 2,
of course.

Can you think of a way of making this function recursive to work with any
number of elements?

- James

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to