DoubleOseven
DoubleOseven

Reputation: 271

Understanding a Haskell function

I am wondering what is the use of (answers entry) in totnChars entry = myLoop (answers entry) . Does it mean that entry must be of type answers? But isn't entry of type Entryt?

type Question = [Char]
type Answer = [Char]
type Music = [Char]
data Entryt = MyEntry {
                       questions :: [Question],
                       answers :: [Answer],
                       music :: Music,
                       time :: Float
                      } deriving (Show, Eq) 



totnChars :: Entryt -> Int
totnChars entry = myLoop (answers entry)

myLoop :: [Answer] -> Int
myLoop [] = 0 
myLoop (x:rest) = (nChars x 0) + (myLoop rest)

Upvotes: 1

Views: 155

Answers (2)

sepp2k
sepp2k

Reputation: 370082

answers is a getter function that retrieves a given entries answer list, so totnChars entry = myLoop (answers entry) defines a function that takes an entry and applies myLoop to that entry's answer list.

Does it mean that entry must be of type answers?

No. The syntax to say that something must be of a given type would be expression :: Type, but answers isn't a type. Type names always start with capital letters in Haskell. You can introduce a type variable named answers, but there'd be no point in that. And that's absolutely not what's happening here. answers entry is just a plain old function application.

But isn't entry of type Entryt?

Yes, it is.

Upvotes: 5

isekaijin
isekaijin

Reputation: 19742

answers doesn't have type [Answer]. It has type Entryt -> [Answer].

“But why?” You may ask.

Each Entryt has its own list of answers, which may vary from one Entryt to another. Thus, answers is a function that takes an Entryt and returns its list of answers.

Upvotes: 3

Related Questions