[Haskell-beginners] first number is a list

Mats Rauhala mats.rauhala at gmail.com
Mon Jun 27 14:33:49 CEST 2011


On 12:24 Mon 27 Jun     , Roelof Wobben wrote:
>  Oke,  Now figure out how I can find the 3 in the list [1,2,3,4] I was thinking about using tail [1,2,3,4] and after that use last [1,2,3] So something like last [ tail [1,2,3,4] Or : let outcome = tail [1,2,3,4]let outcome2 = last [outcome]

tail returns the list except for the head. So for example the list
[1,2,3,4] becomes [2,3,4]. Using last on that would return 4, not 3.
However the function init returns the list except for the last item, so
using init on [1,2,3,4] would return [1,2,3] and then using last on that
would return the 3 you wanted. So for example:

 ghci> last $ init [1,2,3,4]
 3

But Data.List exports a function `find :: (a -> Bool) -> [a] -> Maybe
a`, which you can use to find 3.

 ghci> find (== 3) [1,2,3,4]
 Just 3

Another way could be using head and dropWhile:

 ghci> head $ dropWhile (/= 3) [1,2,3,4]
 3



-- 
Mats Rauhala
MasseR
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110627/912b80f2/attachment.pgp>


More information about the Beginners mailing list