1
votes
test n = (sum s)*4+2*(n-1)*((l')^2)-2*(n-1)*(l')
    where 
      p =sort $[ m | a<-[1..(n-1)],b<-[1..(n-1)],let m= (b/a), (a^2+b^2< (n^2))]
      l'= length p
      s = (product a) : next a (group p)
        where 
          a = [(n-1),2*(l')+(n-2)] 
          next [x,y] (z:z':zs) = case (null zs) of
            False -> (x')*(y')*l : next [x',y'] (z':zs)
            True -> (x')*(y')*l :[]
            where 
              l  = length z
              x' = x+l
              y' = y-length z'

Why does the above code give the following error:

No instance for (Fractional Int) arising from a use of ‘/’ In the expression: (b / a)

In an equation for ‘m’: m = (b / a)

In the second argument of ‘($)’, namely

 ‘[m |
    a <- [1 .. (n - 1)],
     b <- [1 .. (n - 1)],
     let m = (b / a),
    (a ^ 2 + b ^ 2 < (n ^ 2))]’

But when I substituted n=3 in the code by hand:

test' = (sum s)*4+2*(3-1)*((l')^2)-2*(3-1)*(l')
    where 
      p = sort $[ m | a<-[1..(3-1)],b<-[1..(3-1)],let m= (b/a), (a^2+b^2< (3^2))]
      l'= length p
      s = (product a) : next a (group p)
        where 
          a = [(3-1),2*(l')+(3-2)] 
          next [x,y] (z:z':zs) = case (null zs) of
            False -> (x')*(y')*l : next [x',y'] (z':zs)
            True -> (x')*(y')*l :[]
            where 
              l  = length z
              x' = x+l
              y' = y-length z'

Then it can be run in GHCi; what is happening?

1
You may find it interesting to know that one thing type theorists typically prove about their systems is that beta reduction respects typing; that is, if (\x -> e) e' can be given type t, then e[e'/x] (the term where we replace x with e' everywhere in e) can also be given type t. However, the reverse is generally not true: e[e'/x] may have more types than (\x -> e) e'. In particular when e' is polymorphic -- as 3 is in your example -- but is forced to be monomorphic by function application.Daniel Wagner

1 Answers

3
votes

When you typed n, you forced it to become Int with your expressions. Thus, b and a became Ints, which became problematic in a/b.

When you wrote 3, the literal being polymorphic allowed some expressions to use Int, and some to use some other Fractional a => a. The 3s used across that function are simply different values.

Creating a different value such as nP = fromIntegral n should allow you to use n in every context, because nP shouldn't become rigidized by any expression.