im new to haskell and when i tried some basic syntax it seems to not work the way it is supposed to work. ive tried a couple of things but nothing seems to be working properly. im starting to assume that its some issue with the compiler. if so maybe help with diagnosing the issue ig.
main = do
fact:: Int -> Int
fact n
| n==0 = 1
| n==1 = 1
| otherwise = n*fact(n-1)
main.hs:5:9: error: parse error on input `|'
|
5 | |n==0 = 1
| ^
The function seems to give a parse error. ive tried altering the white space and indentations in all possible ways but nothing seems to be working
main::IO
main = do
fact:: Integer -> Integer
fact 0 = 1
fact n = n*fact (n-1)
i then tried this and this gives parse error on “=”. something is wrong again…
main.hs:4:12: error:
parse error on input `='
Suggested fix:
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
|
4 | fact 0 = 1
| ^
1
It does not make much sense to define a function in the do expression. You define it outside, or in a where
clause, and then call it in the main
, like:
fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n - 1)
main = print (fact 5)
or with:
main = do
print (fact 5)
where
fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n - 1)
but the do
is useless, since we don’t “bind” multiple IO
expressions together.
If you had some reason to define the function in the do
expression, it must be part of a let
statement.
main = do
let fact:: Int -> Int
fact n
| n==0 = 1
| n==1 = 1
| otherwise = n*fact(n-1)
...
(Additionally, the guards must be indented to indicate they are part of the definition begun by fact n
.)