Reputation: 357
I'm new to Haskell, but I'm trying to add a float to all members of an integer list in Haskell and I'm having trouble getting past the errors and such.
Basically
addAll xs = map (+3.5) xs
Where xs is an integer list.
Upvotes: 0
Views: 953
Reputation: 15967
It can be [Float]
or [Integer]
- in Haskell you should be explicit about that.
[Integer]
You need either to round
the floating point number before you multiply:
map (+ (round (3.5 :: Float))) [1..(10 :: Integer)]
[Float]
Or convert the integers with fromInteger
[3.5 + fromInteger x | x <- xs]
map ((+3.5) . fromInteger) xs
as adding numbers only works if both summands are of the same type, you can see this in the type signature
(+) :: Num a => a -> a -> a
all a
s have to be the same and be an instance of the Num
-typeclass (much alike an interface in Java, if you have experience with that).
Note: There is no automatic conversion in Haskell1.
1: Except for numeric literals like 0,1,2…
they are converted using fromInteger
, numeric literals like 1.1
,2.2
etc. are converted by fromRational
and String
literals when you enable OverloadedStrings
with fromString
.
Upvotes: 5
Reputation: 30736
You'll need to convert each Integer
to a Float
before you can add a Float
to it.
You can use fromInteger
for this. Its type is
Num a => Integer -> a
which, for our purpose here, specializes to
Integer -> Float
So here's what the addAll
function looks like:
addAll :: [Integer] -> [Float]
addAll xs = map (\x -> fromInteger x + 3.5) xs
Example usage in GHCi:
λ> addAll [1, 2, 3]
[4.5,5.5,6.5]
Upvotes: 7