logo

Crowdly

Browser

Add to Chrome

Defining functions We have seen how to call functions. Now we will tackle the...

✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.

Defining functions

We have seen how to call functions. Now we will tackle the flip side: how to define a function.

What are the ingredients for defining a function we already know from other programming languages? We need at least:

  • a name for the function
  • names for parameters, if any
  • the body of the function (defining the implementation)

For programming languages oriented towards the "imperative" paradigm, the body of the function is a sequence of statements (usually, one per line, possibly terminated by semicolons). For functional programming languages, the body is just an expression.

Compare this Python function:

def yell(name):

return name + "!"

and this definition in Haskell:

yell name = name ++ "!"

After defining it, we can use it like we did before with other functions:

ghci> yell "Luca"

"Luca!"

Despite the conciseness and the lack of explicit types in the definition, every function in Haskell has a statically known type! We were able to omit it because Haskell's type inference mechanism, which tries to figure out the types when they are left implicit.

Indeed, we can ask for the type of the yell function in the REPL:

ghci> :t yell

yell :: [Char] -> [Char]

Sure enough, the function yell takes in a String (list of characters) and produces a list of characters.

Go ahead and define a function isUSI with a parameter named univName which returns True iff the provided university name is "USI". You can use the familiar == operator to compare two expressions. Try to call it with a couple of different arguments to verify that it works as intended:

ghci> isUSI "ETH"

False

ghci> isUSI "USI"

True

Write the definition of the isUSI function:

More questions like this

Want instant access to all verified answers on www.icorsi.ch?

Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!

Browser

Add to Chrome