Haskell - finding k'th element from end, and haskell's can't match the pattern -



Haskell - finding k'th element from end, and haskell's can't match the pattern -

i'm trying implement recursive function returns k's element end.

this attempt:

kelementfromend :: int -> [x] -> x kelementfromend _ [] = error "cannot request k item empty list" kelementfromend k [x] | k < 0 = error "k must non negative" | k == 0 = lastly [x] | otherwise = kelementfromend (k-1) (init [x])

and error i'm receiving:

*main> kelementfromend 2 [1,2,3] *** exception: ex2.hs:(4,1)-(8,54): non-exhaustive patterns in function kelementfromend

i don't understand why haskell can't match pattern. what's going on i'm not understanding?

thanks

you've matched empty lists ([]) , single element lists ([x]). think mean replace [x], pattern matches single element list , assign's single value x, xs, pattern matches list not matched. like

kelementfromend :: int -> [x] -> x -- pattern matches empty list kelementfromend _ [] = error "cannot request k item empty list" -- pattern name, matches else -- i.e. non-empty lists kelementfromend k xs | k < 0 = error "k must non negative" | k == 0 = lastly xs | otherwise = kelementfromend (k-1) (init xs)

and work as

> kelementfromend 0 [1..5] 5 > kelementfromend 4 [1..5] 1 > map (\i -> kelementfromend [1..10]) [0..9] [10,9,8,7,6,5,4,3,2,1]

haskell

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -