Quelquelquel
Quelquelquel

Reputation: 3

Function that returns the element at a given index

How can I implement a function that returns ns element from a list with signature like this? I know usual way with !! operator, but here is Natural type, so Haskell can't match it to expected Int.

indexed :: Natural -> [a] -> a

Upvotes: 0

Views: 275

Answers (3)

jpmarinier
jpmarinier

Reputation: 4733

Maybe just this:

import  Numeric.Natural

indexed :: Natural -> [a] -> a
indexed nat xs = (xs !! (fromIntegral nat))

Trying it under ghci:

 λ> 
 λ> z = 0 :: Natural
 λ> :t z
z :: Natural
 λ> z
0
 λ> 
 λ> indexed z [1..3]
1
 λ>

Upvotes: 1

Rayan Hatout
Rayan Hatout

Reputation: 640

I'm assuming you're referring to the Numeric.Natural package

This is a bit of a hack but you could do:

indexed :: Natural -> [a] -> a
indexed n xs = xs !! (fromInteger (toInteger n))

Upvotes: 1

Ackdari
Ackdari

Reputation: 3498

I assume that Natural is Numeric.Natural. Then you can simply do

indexed :: Natural -> [a] -> a
indexed 0 (x:_) = x
indexed _ [] = error "OutOfRange"
indexed n (_:xs) = indexed (n-1) xs

Upvotes: 1

Related Questions