basti12354
basti12354

Reputation: 2520

Function for list, give me the item at position x

I want to create a function in haskell, that gives me the item at position x.

For example:

   [1..10] `give` 3    => should give me 4

In java this is no problem, but how can I handle this in Haskell

    give :: [b] -> Integer -> Maybe b
    give ????

Upvotes: 0

Views: 103

Answers (3)

RussellStewart
RussellStewart

Reputation: 5443

Just another fun solution in addition to those above:

give xs n = head $ iterate tail xs !! n

Upvotes: 0

Benesh
Benesh

Reputation: 3428

I tend to avoid explicit recursion when possible. Function composition results in a more readable code, and composing standard library function results in a reliable code. So here's my version:

import Data.Maybe

give :: [a] -> Integer -> Maybe a
give xs n = listToMaybe $ drop n xs

Explanation: drop n xs drops the first n elements, so drop 3 [1..5] returns [4,5]. listToMaybe returns Nothing for an empty list, and Just x for (x:_).

Upvotes: 2

donutmonger
donutmonger

Reputation: 154

Try this out, it works for me.

give :: [b] -> Integer -> Maybe b
give [] _ = Nothing
give (x:xs) 0 = Just x
give (x:xs) index = give xs (index - 1)

Upvotes: 1

Related Questions