 # Haskell – Function

Table of Contents

Preface

You may not know it, but since the first part up until now we’ve been using functions (Function). For example, the * sign is a function to multiply 2 numbers, and we put the 2 numbers to be multiplied on the left and right of the `*`. However, most functions that do not take integer arguments are called by placing the parameters to the right of the function name.

## How to call the function

Usually in imperative languages ​​we call a function by calling its name, followed by a pair of signs `()`, inside are parameters, separated by commas.

In Haskell, we call the function by naming the function, followed by the parameters, separated by a space mark. For example:

```ghci> succ 8
9
```

The succ function returns the next value of the passed value, such as `succ 8 = 9`, `succ 'a' = 'b'`, `succ 1.1 = 2.1`

Passing multiple parameters, we just write the parameters separated by 1 space mark. For example:

```ghci> min 9 10
9
ghci> min 3.4 3.2
3.2
ghci> max 101 101
101
```

Jaw `min` get the smallest number between 2 numbers, function `max` get the largest number between 2 numbers.

Function calls always have a higher priority than regular statements, that is, in a statement with many statements, the function calls will be executed first. For example:

```ghci> succ 9 + max 5 4 + 1
16
ghci> (succ 9) + (max 5 4) + 1
16
```

In the above code then `succ 9` and `max 5 4` will be called first and then add the results of these two functions together and + 1. Both statements are used `()` and do not use `()` all have the same priority.

If we want to execute the following commands first then we have to wrap them in parentheses `()`. For example:

```ghci> max 5 3 * 2
10
ghci> max 5 (3 * 2)
6
```

If a function accepts 2 Parameters then we can write these 2 parameters on the left and right sides of the function name. However, with this call, we must enclose the function’s name in pairs of signs ```` Because Haskell does not know what parameters to pass first and which parameters to pass later. For example:

```ghci> 5 `max` 3
5
ghci> max 5 3
5
```

## Function definition

To define a function, we first write it like a function call, then add an = sign and start writing statements inside the function. For example:

```ghci> doubleMe x = x + x
```

In the above code we define the function `doubleMe,` accept 1 parameter named `x`. This function will x2 this parameter. Then we can use it as usual:

```ghci> doubleMe 9
18
ghci> doubleMe 8.3
16.6
```

We can use the above function within the definition of another function. For example:

```ghci> tripleMe x = doubleMe x + x
ghci> tripleMe 3
9
```

Hope this helps!

Source link