I am trying to write a function that retrieves the nth element in a list.
Here's what I have so far:
main :: IO ()
main = do print (nth 3 [1,2,10])
nth _ [] = []
nth a (x:xs)
| (a == 1) = x
| otherwise = nth (a-1) xs
This is the error I get:
Error occurred
ERROR line 2 - Cannot justify constraints in explicitly typed binding
*** Expression : main
*** Type : IO ()
*** Given context : ()
*** Constraints : (Show a, Num [a])
nth(this is a good practice anyway). That should make the problem here more apparent.nthto return an element of the list, you surely want it to have typeInt -> [a] -> a, right? Well, your first definition,nth _ [] = [], is a list (or "returns a list", if you prefer), so it's a definition of a function of typeInt -> [a] -> [a]. So what shouldnthdo with an empty list? That's a good question! One way is to simply have it fail, another is to give it return typeMaybe a, withNothingreturned in case the list is too short.nthis supposed to be, the compiler figures out some amazing (and often rather ridiculous) signature and only notices a the call site (here,main) that it's bogus. That's why you get an error message demandigNum [a], which is obviously weird and one of the typical signs that you've made an error somewhere else and didn't build a safety-net in form of an explicit type signature there.