0

I have some data defined as

{-# LANGUAGE RankNTypes      #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies    #-}

module Test where

import           Control.Lens
import           Data.MonoTraversable

data Custom = Custom { _a :: Maybe Float
                     , _b :: Maybe Float
                     }
makeLenses ''Custom


type instance Element Custom = Maybe Float

instance MonoFunctor Custom where
    omap f (Custom ja jb) = Custom (f ja) (f jb)

data MainI = MainI { _name   :: Maybe String
                   , _dTypes :: Maybe Custom
                   }
makeLenses ''MainI

I have a function defined like this

addEm :: MainI -> MainI -> MainI
addEm toGet toSet = toSet & dTypes %~ (\x -> emFunctions <$> x <*> baseTypes)
    where baseTypes =
             (toGet & (dTypes . _Just)  %~ (omap (\x -> pure (* 1.5) <*> x))) ^. dTypes 

which just takes each value inside Custom, adds 1.5 times the values in toGet into the values in toSet.

It does that with this helper function

emFunctions :: Custom -> Custom -> Custom
emFunctions toGetC toSetC = toSetC
     & a %~ (\x -> (+) <$> x <*> toGetC ^. a)
     & b %~ (\x -> (+) <$> x <*> toGetC ^. b)

So I was wondering if there's a better way of doing this?

Particularly doing it without the helper function.


Also a related question: Would it be possible to sum up the Custom data? As in if _a == 5.5 and _b == 5.0 the sumCustom function would return 10.5

atis
  • 881
  • 5
  • 22
  • I struggle with this because it looks completely overcomplicated, very hard to read and not worth the effort. Perhaps your actual case is more complicated but what is wrong with: `emFunctions (Custom a1 b1) (Custom a2 b2) = Custom (a1 + a2) (b1 + b2) where (+) = liftA2 (+)`? – Dan Robertson Jan 13 '19 at 18:12
  • Nothing really. Yours is a version of helper function without the use of lenses. My actual case has very deeply nested structures, so the reason I'm using lenses is to make dealing with that a bit easier. The reason behind my question was to streamline adding structures with a function that doesn't rely on unfolding multiple structures to deal with the actual target. My idea was to mainly define a general function and use lenses to just point it at different parts/different depths of the those structures. – atis Jan 13 '19 at 18:34

0 Answers0