4
votes

I am new to programming and to Haskell. I'm having trouble understanding how to define a function. Let's say I want a function that will return element in position a of a list [b]. For a specific a and [b] I can do this in the interpreter:

Prelude> [2, 3, 5, 6] !! 1
Prelude> 3

But I run into trouble if I try to make a function, either in the interpreter or in a text editor that is then loaded:

Prelude> let getElement a [b] = [b] !! a 
Prelude> getElement 1 [2, 3, 5, 6]
***Exception: <interactive>:17:5-27: Non-exhaustive pattern in function getElement
1
I have no compiler at reach, but you also could do a calls of head on [b]. Then you would learn some recursion.mike
use b instead of [b]soulcheck
You'll need let getElement a b = b !! a. By [b] you mean a list of one element which is b. Read a Haskell tutorial, it will help.nickie
@mike, that's tail you need a applications of, not head.Rotsor
if you use ghci, i'd recommend to the changes in your editor and save them in a .hs file which you the load using :r <filename>.hs; the error message you get some input combinations are not covers by the function definition you have providedjev

1 Answers

6
votes

let getElement a [b] = [b] !! a

Your function takes one argument a of type Int, since (!!) second parameter is an Int, and [b] pattern matches on a list with one element.

It looks like you were trying to tell the complier that the second parameter should be a list. To do this you normally use the type signature.

In a file:

getElement :: Int -> [b] -> b
getElement a bs = bs !! a

This type of function is considered partial since you can give it an integer that causes the function to fail and throw an exception, such as a negative number or trying to access an index larger then the list. This chapter in real world Haskell has some information on partial function. The Haskell wiki in on the programming guidelines page has some advise too.

You may want to look at the safe package and how they define headMay for a total, rather then partial, implementation.

Edit: b changed to bs as recommend by Rein Henrichs below, as he points out it does make it easier to read and is a rather common idiom.