Squanchy
Squanchy

Reputation: 133

how to create your own function that adds a string and a float in Haskell?

Lear ingredientes Haskell and I am trying to add a string and an a float using a type declaration. I think this is built into Haskell, but I wanted to challenge myself so that I would understand how things work deeper, below is what I have but I get and error saying.

Prelude> addFloat "3.14" 1.6

<interactive>:7:1: error:
* No instance for (Num [Char]) arising from a use of `addFloat'
* In the expression: addFloat "3.14" 1.6
  In an equation for `it': it = addFloat "3.14" 1.6

<interactive>:7:17: error:
* No instance for (Fractional [Char])
    arising from the literal `1.6'
* In the second argument of `addFloat', namely `1.6'
  In the expression: addFloat "3.14" 1.6
  In an equation for `it': it = addFloat "3.14" 1.6
Prelude>

Here is my code:

addFloat :: (String a) => a -> Float -> a
addFloat x y = x + y

Not quite understanding what I am doing wrong?

Upvotes: 0

Views: 145

Answers (1)

chi
chi

Reputation: 116139

Haskell never performs type conversions automatically. If you want to convert a string into a float, you need to use read explicitly.

addFloat :: String -> Float -> Float
addFloat x y = read x + y

(I'm not sure this is a good idea for a function though.)

If you need a string as output, convert the resulting float to string

addFloat :: String -> Float -> String
addFloat x y = show (read x + y)

Further, String is a type, not a type class, so you can not write (String a) => ....

Upvotes: 2

Related Questions