简体   繁体   中英

Function guard syntax in Haskell

fib::Int->Int
fib n
    n==0        = 1
    n>1     = error "Invalid Number"

this function gives me a error

Syntax error in declaration (unexpected symbol "==")

im not sure whats wrong with the function when compare to the reading material it looks the same

You're missing some of the syntax:

fib :: Int -> Int
fib n 
    | n == 0  = 1
    | n > 1   = error "Invalid Number"

This can also be written without the first newline:

fib :: Int -> Int
fib n | n == 0  = 1
      | n > 1   = error "Invalid Number"

This function is more naturally expressed with pattern matching:

fib :: Int -> Int
fib 0 = 1
fib n | n > 1 = error "Invalid number"

and you might be interested in the catalogue of fibonaccis .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM