1. 2

I have been working forwards from MLsub type inferencing. I gave it a typeclass-inspired mechanism that allows overloading the arithmetic operators.

I can give it fibonacci as an input:

fibonacci(n)
    if gt(n, 2) then
        add(fibonacci(sub(n,1)), fibonacci(sub(n,2)))
    else 1

The results look like this:

add :: (a, b) -> c
  add (a, b) -> c
sub :: (a, b) -> c
  sub (a, b) -> c
gt :: (ord(), ord()) -> bool()
fibonacci :: (ord() & a) -> (int() | b)
  add (int() | b, int() | b) -> b
  sub (a, int()) -> (ord() & a)
  sub (a, int()) -> (ord() & a)

In the fibonacci, the b variable no longer has external inputs, so the lone add can be eliminated by selecting an implementation for it. The two sub here have similar flow structure, proposing that they can be safely merged.

This week I’m going to add in the following dispatch table and figure out the rest of the details there is in getting this to eliminate these constraints correctly.

add (int(), int()) -> int()
add (rational(), rational()) -> rational()
add (rational(), int()) -> rational()
add (int(), rational()) -> rational()

Unfortunately I’m not sure how to solve the last problem there will be. How to make the dispatch engine good enough that it satisfies the demands for both numerical and symbolic algebra?

A dispatch table with 4 entries in it probably won’t be enough.

  1.  

  2. 4

    I made a post on the /r/haskell subreddit about avoiding typeclass design mistakes. You might be interested in the post: https://www.reddit.com/r/haskell/comments/7vand6/avoiding_type_class_design_mistakes/

    The biggest takeaway for me was that Haskell got the numerical typeclasses completely wrong. Instead of using different sets of numbers (rational, integer, fractional, etc.) you should use algebraic structures instead. This is what Purescript ended up doing. So the (+) and (*) operations are declared in the “Semiring” type class, (-) is defined in the “Ring” type class, etc. There’s a helpful diagram of the hierarchy on this StackOverflow post: https://stackoverflow.com/questions/37667240/is-there-a-purescript-typeclass-generalizing-integers

    Using the algebraic structures brings the numeric operations more in line with the other typeclasses which are based on algebraic structures.