Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - get nth element without "!!"

Tags:

haskell

I need to get the nth element of a list but without using the !! operator. I am extremely new to haskell so I'd appreciate if you can answer in more detail and not just one line of code. This is what I'm trying at the moment:

nthel:: Int -> [Int] -> Int
nthel n xs = 0
let xsxs = take n xs
nthel n xs = last xsxs

But I get: parse error (possibly incorrect indentation)

like image 345
user43051 Avatar asked Apr 12 '13 21:04

user43051


1 Answers

There's a lot that's a bit off here,

nthel :: Int -> [Int] -> Int

is technically correct, really we want

nthel :: Int -> [a] -> a

So we can use this on lists of anything (Optional)

nthel n xs = 0

What you just said is "No matter what you give to nthel return 0". which is clearly wrong.

let xsxs = ...

This is just not legal haskell. let ... in ... is an expression, it can't be used toplevel.

From there I'm not really sure what that's supposed to do.

Maybe this will help put you on the right track

nthelem n [] = <???> -- error case, empty list
nthelem 0 xs = head xs
nthelem n xs = <???> -- recursive case

Try filling in the <???> with your best guess and I'm happy to help from there.

Alternatively you can use Haskell's "pattern matching" syntax. I explain how you can do this with lists here.

That changes our above to

nthelem n [] = <???> -- error case, empty list
nthelem 0 (x:xs) = x --bind x to the first element, xs to the rest of the list
nthelem n (x:xs) = <???> -- recursive case

Doing this is handy since it negates the need to use explicit head and tails.

like image 54
Daniel Gratzer Avatar answered Nov 15 '22 06:11

Daniel Gratzer