HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Simplification of consecutive `map`s

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mapconsecutivesimplification

Problem

I've written the following code:

{- ...
   ...
   ... -}

data Ellipsoid
data Halfplane
data Intersection

data PointSet s a where
    Halfplane :: RealFrac a =>
                 a -> a -> a -> (a -> a -> Bool) -> a ->
                 PointSet Halfplane a
    Ellipsoid :: RealFrac a =>
                 a -> a -> a -> (a -> a -> Bool) -> a ->
                 PointSet Ellipsoid a
    Intersection :: [PointSet s a] -> PointSet Intersection a

type TestFunc a = RealFrac a => (a -> a -> a ->  Bool)

test :: (Show  a) => PointSet t a -> TestFunc a
test (Ellipsoid a b c f r) = f'
                       where f' z y x = ((x/a)^2 + (y/b)^2 + (z/c)^2) `f` r
test (Halfplane a b c f t) = f'
                       where f' z y x = (a*x + b*y + c*z) `f` t
test (Intersection ps) =     f'
        where f' z y x = and . map ($ x) $ map ($ y) $ map ($ z) ts
              ts = map test ps


In particular I'd like to have input on f' z y x = and . map ($ x) $ map ($ y) $ map ($ z) ts, whether there is a way to express this more succinctly.

Of course, I'm happy about any other comment as well.

Solution

The expression

and . map ($ x) . map ($ y) . map ($ z) . map test $ ps


contains several map calls connected with .. But since map f . map g === map (f . g), we can simplify it as

and . map (($ x) . ($ y) . ($ z) . test) $ ps


or more concisely

and . map (\g -> test g x y z) $ ps


Also and . map p can be simplified by all, so finally we get

all (\g -> test g x y z) ps


Just one more note, please post code that compiles, especially for CR, it's much easier to work with; see http://sscce.org/

Code Snippets

and . map ($ x) . map ($ y) . map ($ z) . map test $ ps
and . map (($ x) . ($ y) . ($ z) . test) $ ps
and . map (\g -> test g x y z) $ ps
all (\g -> test g x y z) ps

Context

StackExchange Code Review Q#55231, answer score: 2

Revisions (0)

No revisions yet.