Why Does Integer Arithmetic in Haskell Seem Inconsistent?

Click For Summary
SUMMARY

The forum discussion addresses the inconsistencies in integer arithmetic in Haskell, specifically when using the `div` function in Hugs (Haskell98 mode). The expression `div -6 4` results in an error due to type inference issues, while `div (-6) 4` correctly evaluates to -2. Additionally, the expression `-6 \`div\` 4` evaluates to -1, and `(-6) \`div\` 4` evaluates to -2, indicating that Haskell's interpretation is influenced by operator precedence and associativity. The conclusion is that the right-associative nature of the `div` operator leads to different results based on how expressions are grouped.

PREREQUISITES
  • Understanding of Haskell syntax and semantics
  • Familiarity with Hugs and Haskell98 mode
  • Knowledge of operator precedence and associativity in programming languages
  • Basic concepts of integer arithmetic in functional programming
NEXT STEPS
  • Research Haskell operator precedence and associativity rules
  • Explore the differences between Hugs and GHC (Glasgow Haskell Compiler)
  • Learn about type inference in Haskell and how it affects function calls
  • Investigate the behavior of other arithmetic functions in Haskell
USEFUL FOR

Haskell developers, functional programming enthusiasts, and anyone troubleshooting integer arithmetic issues in Haskell.

gnome
Messages
1,031
Reaction score
1
Can anybody explain what appear to be discrepancies in the way the following expressions are interpreted by Hugs (Haskell98 mode) ?

Code:
Main> div -6 4
ERROR - Cannot infer instance
*** Instance   : Num (b -> a -> a -> a)
*** Expression : div - fromInt 6 4

Main> div (-6) 4
-2
Main> -6 `div` 4
-1
Main> (-6) `div` 4
-2
 
Computer science news on Phys.org
Never mind.

I guess it must be right-associative, so -6 `div` 4 is interpreted as -(6 `div` 4).
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 29 ·
Replies
29
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
Replies
13
Views
3K
  • · Replies 16 ·
Replies
16
Views
3K
  • · Replies 55 ·
2
Replies
55
Views
8K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
3
Views
2K