1

I just began learning haskell a few days ago and I started with the first problem in "99 haskell questions" a few minutes ago.

The first one is fairly simple, to get the last element from a list. I was trying out various ways to solve, but I encountered the above error when I tried this little guy:

getLast = foldr1 $ flip const

I understand that this error occurs due to haskell being unable to infer the type of the function getLast and all I need to do is add an explicit type annotation for getLast.

But strangely, if I write the above code in GHCi, it works! How is this possible? Is somehow GHCi Clairvoyant and be able to deduce types now?

What are the major differences between writing a code directly in GHCi and writing haskell code in a .hs file and loading it?

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • 4
    You're running into the monomorphism restriction, if you put {-# LANGUAGE NoMonomorphismRestriction #-} at the top of your file it will work. See [here](https://wiki.haskell.org/Monomorphism_restriction) – pdexter Jun 05 '16 at 15:59
  • 1
    GHCi runs with `-XNoMonomorphismRestriction` by default, GHC does not. Another way to get rid of the error is to ditch the pointfree style. `getLast xs = foldr1 (flip const) xs` works too. You can reproduce the same general error by declaring e.g. `foo = show`, while `foo x = show x` is OK. – n. m. could be an AI Jun 05 '16 at 16:09
  • oops sorry, forgot to include the error : Ambiguous type variable ‘t0’ arising from a use of ‘foldr1’ And thanks for your answers n.m and pdexter :) But, how does ditching pointer free style make the code suddenly work? Is this also because of the monomorphism restriction ? – Chakravarthy Raghunandan Jun 05 '16 at 16:13
  • @ChakravarthyRaghunandan Yes. The MR does not apply to function bindings (i.e. non-pointfree), or to bindings with an explicit type annotations. The rationale is quite involved, leading to surprising results sometimes. Adding type annotations is good style, anyway, so in real-world code the MR is not such a big deal. – chi Jun 05 '16 at 16:20
  • I understand the issue now, thanks everyone for the replies. Cheers – Chakravarthy Raghunandan Jun 05 '16 at 16:36
  • See especially the section on extended defaulting in the marked duplicate. – Daniel Wagner Jun 05 '16 at 17:58

0 Answers0