Yogesh Patel
Yogesh Patel

Reputation: 11

No instance for (Fractional [Double]) arising from the literal ‘1.0’

For class, we have to write some code for a given set of problems. One of these problems is to create an identity matrix in the form of a [[Double]] So far, I have come up with the following code. However, when I try to compile I get the following error, not sure of what I did wrong or what it means

CODE:

ident :: Int -> [[Double]]
ident x = identHelper x 0

identHelper :: Int -> Int -> [[Double]]
identHelper y z
  | z == 0 = ([1.0] ++ replicate (y-1) 0.0) : identHelper y 1
  | y == z = replicate (y-1) 0.0 : 1.0
  | otherwise = (replicate z 0.0 ++ [1.0] ++ replicate (y-z-1) 0.0) : identHelper y (z+1)

ERROR:

    • No instance for (Fractional [[Double]])
        arising from the literal ‘1.0’
    • In the second argument of ‘(:)’, namely ‘1.0’
      In the expression: replicate (y - 1) 0.0 : 1.0
      In an equation for ‘identHelper’:
          identHelper y z
            | z == 0 = ([1.0] ++ replicate (y - 1) 0.0) : identHelper y 1
            | y == z = replicate (y - 1) 0.0 : 1.0
            | otherwise
            = (replicate z 0.0 ++ [1.0] ++ replicate (y - z - 1) 0.0)
                : identHelper y (z + 1)

Upvotes: 0

Views: 103

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120731

The problem is

           replicate (y-1) 0.0 : 1.0

BTW you can (and should) always leave away trailing zeroes, so

           replicate (y-1) 0 : 1

For example, say y=4. Then this reads

           [0,0,0] : 1

So you're trying to prepend the list [0,0,0] before the... list? 1. How is 1 supposed to be a list?

I'm not sure what you want there, but one plausible option is [[1]].

Upvotes: 5

Related Questions