user1022241
user1022241

Reputation:

Expected Type and Main

Total Haskell noob here. I have a simple function, and a main. I don't have any idea what this error means:

Couldn't match expected type `IO t0' with actual type `Bool'
In the expression: main
When checking the type of the function `main'

when compiling the code:

is_instructor :: String -> Bool
is_instructor "Jeremy Erickson" = True
is_instructor x = False

main :: Bool
main = is_instructor "foo"

Upvotes: 2

Views: 270

Answers (3)

Daniel Fischer
Daniel Fischer

Reputation: 183873

main is the thing that gets called when you run your programme. It is expected that a programme does in some way interact with the outside world (read input, print output, such things), therefore it's reasonable that a main should have the type IO something. For reasons of type safety and simplicity, that is a requirement in Haskell, like main in Java must have type public static void main(String[] arrgh).

You probably wanted you value to be printed, so

main :: IO ()
main = print $ is_instructor "foo"

would be what you want.

Upvotes: 4

Luis Casillas
Luis Casillas

Reputation: 30227

You've certainly heard that Haskell is a purely functional language. This means (among other things) that the only thing that a function can do in Haskell is compute a result that depends on the arguments; a function can't do I/O, or have a result that depends on something other than the arguments' values.

But Haskell allows you to write programs that do I/O and other effectful things. How is this possible? Well, what it means is that in Haskell, things that perform I/O or side effects are not functions; they are something else. People often refer to them as actions. I/O actions in Haskell have types of the form IO a.

The error you're getting here is that main, the entry point to a Haskell program, is required to be an action of type IO (). But is_instructor is a function of type String -> Bool, and is_instructor "foo" is a Bool.

Haskell doesn't allow you mix and match pure functions and actions haphazardly like that. Applying a function and executing an action are two different things, and will require different code.

Upvotes: 2

leftaroundabout
leftaroundabout

Reputation: 120711

You can't have a main function with type Bool, it always needs to be in the IO monad. What you probably want is something like printing out this boolean value. Then just do that!

main :: IO()
main = print $ is_instructor "foo"

Upvotes: 2

Related Questions