[Haskell-beginners] Improve my lambda expressions

Frerich Raabe raabe at froglogic.com
Mon Jun 26 11:04:27 UTC 2017


On 2017-06-26 11:38, PATRICK BROWNE wrote:
> The code below provides a distance function that works for points and moving 
> point.
> I am happy with the result, but I have a problem with the lambda 
> expressions.

[..]

> -- Sttic points
> p1, p2 :: Point Float
> p1 = Point 0.0 0.0
> p2 = Point 4.0 4.0
> d = dist p1 p2
> 
> -- Moving points
> mp1, mp2 :: Point Float
> mp1x = (\t -> 4.0 + 0.5 * t)
> mp1y = (\t -> 4.0 - 0.5 * t)
> mp1 = Point (mp1x 2) (mp1y  2)
> mp2x  = (\t -> 0.0 + 1.0 * t)
> mp2y  = (\t -> 0.0 - 1.0 * t)
> mp2 = Point (mp2x 2) (mp2y 2)
> md = dist mp1 mp2

Maybe you could reduce the number of lambda expressions by extracting common 
logic. It seems to me that 'mp1' and 'mp2' are moved versions of the same 
point (2,2) except that they apply different functions to the coordinates. 
These functions follow a pattern (a factor is applied to the component and 
then an 'offset' is added).

For instance, it might be worthwhile to define

   movePoint :: Float -> Float -> Point -> Point
   movePoint offset factor (Point x y) = Point (offset + factor * x) (offset - 
factor * y)

...such that you could then define

md = let p = Point 2 2 in dist (movePoint 4 0.5 p) (movePoint 0 1 p)

-- 
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing


More information about the Beginners mailing list