Tahuru
Tahuru

Reputation: 3

Haskell: "No instance for (Fractional (Maybe Float)) arising from the literal '0.0'"

I'm trying to create a function that given a specific condition will add either 0.0 or Nothing to the end of a list however the compiler won't accept me simply adding the literal number to the list and returns the error quoted in the title.

Here is the code that's returning the error

createDistList :: WAdjList -> Int -> Int -> [Maybe Float] -> [Maybe Float]
createDistList [] i j ys = if i == j then ys ++ [0.0] else ys ++ [Nothing]

The code is extended past this but it's the same error happening again in the same context.

Upvotes: 0

Views: 98

Answers (1)

chepner
chepner

Reputation: 531718

The problem is that ys has type [Maybe Float], not Float. You might expect an error telling you that 0.0 doesn't have type Maybe Float. But it's more complicated than that, because 0.0 itself doesn't have type Float; it has type Fractional a => a.

Because type classes are open, the type checker is willing to believe that maybe 0.0 can provide a value of type Maybe Float. But for that to happen, you need to define a Fractional instance for Maybe Float. You haven't, which is what the error message is telling you.

The solution is to provide the correct value in your function: use Just 0.0, not 0.0.

createDistList :: WAdjList -> Int -> Int -> [Maybe Float] -> [Maybe Float]
createDistList [] i j ys = if i == j then ys ++ [Just 0.0] else ys ++ [Nothing]

or more briefly,

createDistList :: WAdjList -> Int -> Int -> [Maybe Float] -> [Maybe Float]
createDistList [] i j ys = ys ++ [if i == j then Just 0.0 else Nothing]

Upvotes: 3

Related Questions