Reputation: 145
Hi I'm trying to sum a list of tuples into a tuple with the foldl function, I tryed it with using as parameter a lambda expresion but it's giving out a wrong value here the code:
data Point = Point {x,y :: Float}
sumPoint :: [Point] -> (Float,Float)
sumPoint xs = foldl (\(a,b) x-> (0+a,0+b)) (0.0,0.0) xs
It should come out sumPoint [Point 2 4, Point 1 2, Point (-1) (-2)] = (2.0,4.0)
But im getting (0.0,0.0)
How is this making any sense?
Upvotes: 1
Views: 244
Reputation: 26161
To be a little structural you better define operations among Point
type values and then convert the Point
type to Tuple wherever needed. Otherwise you may directly use Tuple and discard the Point
type.
data Point = Point {x,y :: Float} deriving Show
toTuple :: Point -> (Float, Float)
toTuple p = (x p, y p)
addPts :: Point -> Point -> Point
addPts p q = Point (x p + x q) (y p + y q)
sumPts :: [Point] -> Point
sumPts = foldl addPts (Point 0 0)
So what you need is toTuple . sumPts
function.
*Main> :t toTuple . sumPts
toTuple . sumPts :: [Point] -> (Float, Float)
Upvotes: 3
Reputation: 145
I changed it to
sumPoint xs = foldl (\(a,b) (Point x y)-> (x+a,y+b)) (0.0,0.0) xs
The problem was I was ignoring the x and at 0+a is nothing happening.
Upvotes: 2