What are multiple lines in Haskell? operator, function, something else?

I am very new to Haskell and I must say that I am puzzled

I use the prelude GHCi

First you need to create a factorial

Prelude> factorial 0 = 1
Prelude> factorial n = n*factorial(n-1)
Prelude> factorial 2
*** Exception: stack overflow

ends in a stack overflow. Obviously, the recursion did not stop.

Prelude> :t factorial
factorial :: Num t => t -> t

Then, after reading this post How to define a function in ghci in a few lines?

I found out that I need to use either several lines or brackets (by the way, is this an operator?)

Prelude> let { fact 0 = 1 ; fact n = n * fact (n-1) }
Prelude> fact 5
120
Prelude> ::t fact
fact :: (Eq p, Num p) => p -> p

or

Prelude> :{
Prelude| facto 0 = 1
Prelude| facto n = n*facto(n-1)
Prelude| :}
Prelude> facto 4
24
Prelude> :t facto
facto :: (Eq p, Num p) => p -> p

So my question is: why is the first wrong, what happens in this case, why the 2nd and 3rd work, and from the result of the function: t they, apparently, at least lead to the exact same definition.

+4
source share
3 answers

why the first is wrong what happens in this case

.

:

factorial 0 = 1

:

factorial n = n*factorial(n-1)

Haskell , , . , (factorial 0 = 1) . , Haskell factorial 2 -> 2 * factorial 1 -> 2 * 1 * factorial 0 -> 2 * 1 * 0 * factorial (-1) -> ....

2 3

, Haskell . , :t function , .

, GHCi. ghc, , , . (, a 0 = 0, b 0 = 0, a n = n), * ).

+5

ghci , , let. , let . , , , let, ( "" ) , Haskell.

:{ :} ghci , ghci. , let:

:{
let fact 0 = 1
    fact n = n * fact (n - 1)
:}

:

:{
fact 0 = 1
fact n = n * fact (n - 1)
:}

fact , Haskell.

+4

Prelude> factorial 0 = 1
Prelude> factorial n = n*factorial(n-1)
Prelude> factorial 2
*** Exception: stack overflow

The first definition is factorialdiscarded, so the function is defined as

Prelude> factorial n = n*factorial(n-1)

So, you do not have instructions to complete the recursion.

+1
source

Source: https://habr.com/ru/post/1688859/


All Articles