3
votes

In Chapter 3, There is an example called "MySecond.hs", what I really don't understand is code like this:

safeSecond :: [a] -> Maybe a

it always in the first line of file, and delete it causes no trouble. anyone could enlight me with what that means? I am but a newbie to any functional programming language.

3
Here's where it is explained in RWH: book.realworldhaskell.org/read/…Sjoerd Visscher
Have you read Chapters 1 and 2?Ben

3 Answers

8
votes

It is the type annotation. If you don't write it Haskell will infer it.

In this case safeSecond is the name of something. The :: separates the name from the type. It takes a list of type a(a is a type variable this function will work on a list of any type.) -> is function application, and Maybe a is the return type.

Note that 'a' represents a single type so if you pass in a int list you must get a Maybe int out. That is to say all 'a's in the the type must agree.

Maybe is just a type that has two alternatives Just a or Nothing.

5
votes

It's the type signature of the function. It's meant to show what the inputs and outputs of the function are supposed/expected to be. For most Haskell code the compiler can infer it if you don't specify it, but it is highly recommended to always specify it.

Aside from helping you remember what the function should actually do, it's also a nice way for others to get an idea about what the function does.

Besides that, it's also useful for debugging, for instance when the type of the function isn't what you expected it to be. If you have a type signature for that function, you would get an error at the definition site of the function, vs if you don't you'd get one at the call site. see Type Signatures and Why use type signatures

Also since you're reading RWH, Chapter 2 covers this.

2
votes

This is a type annotation; it acts like a function declaration in C.

In Haskell, type declaration is usually not strictly necessary, as Haskell can usually infer a good type from correct code. However, it is generally a good idea to declare types for important values, because:

  • If your code is not correct, you tend get more useful error messages that way (otherwise the compiler can get confused trying to infer your types, and the resulting failure message may not be clearly related to the actual error). If you are getting obscure/verbose error messages, adding type annotation may improve them.
  • Especially as a beginner, declaring important types can make you less confused about what you're doing -- it forces you to clarify your thinking as you write the program.
  • As others have mentioned, type annotation acts as active documentation, making other people less confused about your code. As usual, "other people" may be you, a few months down the road.