How to declare type in a function in Haskell?

Asked

Viewed 69 times

1

Ghci, version 8.6.5: http://www.haskell.org/ghc/ :? for help

I’m studying Haskell on this website.

It uses the type declaration example in functions, but when trying to do the same ghci generates an error.

addThree :: Int -> Int -> Int -> Int 

error: Variable not in Scope: addThree :: Int -> Int -> Int -> Int

1 answer

0


To declare the type of a function you must:

  • define the function and allow the GHC to deduct the type on its own account, or
  • define the type and the function in the same file.

It is likely that you have written only the type but without the definition, which is not valid. If you just want to note down the type and set the function only later, you can use undefined:

addThree :: Int -> Int -> Int -> Int 
addThree = undefined

Note: when I say "only after", I mean you go back in the file, delete undefined and put the desired definition, since in Haskell it is impossible to assign new values to the already defined names, as happens in imperative languages.

  • I figured out what the error was, I can’t define direct function in Ghci, at least not a recursive function and nor assign a type to function. For the same I must create direct in the file . hs same and compile them.

  • @Wesleyr.Guimarães On the contrary, you can yes. Just know how to do it. For example: fact n = if n == 0 then 1 else n * fact (n-1) is recursive and can be set in Ghci. If you want to use pattern matching, you should use :{ and :}, or let { linha um; linha 2; ... }, to define functions of more than one line.

  • That’s what I wanted to know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.