2

In Haskell,

This works perfectly fine:(mod 9) 7. It gives the expected result: remainder when 9 is divided by 7 (2).

Similarly, this works too:(mod 9) 9. It returns 0.

This led me to think that (mod 9 == 0) 9 should return True. However, that hasn't been the case: it threw up an error instead.

THE ERROR:

<interactive>:62:1: error:
    • Couldn't match expected type ‘Integer -> t’
                  with actual type ‘Bool’
    • The function ‘mod 9 == 0’ is applied to one argument,
      but its type ‘Bool’ has none
      In the expression: (mod 9 == 0) 9
      In an equation for ‘it’: it = (mod 9 == 0) 9
    • Relevant bindings include it :: t (bound at <interactive>:62:1)

Please help me understand why (mod 9 == 0) 9 wouldn't return True.

P.S.: I'm convinced that my usage of "return" in Haskell's context is flawed. However, I am just starting out, so please excuse me. (Would be nice if you could correct me if I am, indeed, wrong.)

spideyonthego
  • 123
  • 1
  • 10
  • 1
    Why would it? `mod 9 :: Integral a => a -> a`, while `0 :: Num a => a`. – chepner Dec 31 '17 at 14:55
  • 1
    You appear to be trying to compose `==` and `mod 9`, which would look like `((== 0) . (mod 9)) 9`. – chepner Dec 31 '17 at 14:58
  • Got it! I feel stupid now. On the bright side, Haskell's type system seems so useful in understanding code. Thank you. Should I delete this question? – spideyonthego Dec 31 '17 at 14:58
  • Mmm, I wouldn't. I feel like there is a kernel of a good question here; I'm just not sure how it should be worded :). – chepner Dec 31 '17 at 14:58
  • 1
    `mod 9 == 0` means `(==) (mod 9) 0`, comparing a function (`mod 9`) and a number (`0`). Ignoring that issue, we still have that `(mod 9 == 0) 9` is `(==) (mod 9) 0 9` passing three arguments to `(==)`, which only takes two. – chi Dec 31 '17 at 15:53
  • 1
    Saying e.g. "`mod 9 9` should return 0" is very common. You can also say "`mod 9 9` should evaluate to 0" which is better and more common I think, since there's no implication that `mod` fires missiles and incidentally "returns" `0` (where "return" is from the language of mutable registers, stack, pointers, etc). In other contexts you can pronounce `=` as "is" – jberryman Dec 31 '17 at 18:12

1 Answers1

7

As I mentioned in a comment, it appears that you expect mod 9 == 0 to be a function that takes an argument, passes it to mod 9, then returns the result of the comparison. You can write such an expression, but it's a little more complicated.

>>> ((== 0) . (mod 9)) 9
True

Here, (== 0) . (mod 9) is the composition of two functions, (== 0) and mod 9. The composed function takes its argument, applies mod 9 to it, then applies (== 0) to the result. (Where (== 0) is a short form for \x -> x == 0.)

chepner
  • 497,756
  • 71
  • 530
  • 681