logo

Crowdly

Browser

Додати до Chrome

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

✅ Перевірена відповідь на це питання доступна нижче. Наші рішення, перевірені спільнотою, допомагають краще зрозуміти матеріал.

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:

Більше питань подібних до цього

Хочете миттєвий доступ до всіх перевірених відповідей на www.icorsi.ch?

Отримайте необмежений доступ до відповідей на екзаменаційні питання - встановіть розширення Crowdly зараз!

Browser

Додати до Chrome