fho
fho

Reputation: 6798

How to lift a function to work on lenses?

I currently have defined two functions:

avg :: (Fractional e) => [e] -> e
avg e = uncurry (/) $ foldl' (\(a,l) v -> (a+v,l+1)) (0.0,0.0) e

avgOf :: (Fractional a) => Getting (Endo (Endo (a, a))) s a -> s -> a
avgOf g s = uncurry (/) $ foldlOf' g accfun (0.0,0.0) s
  where accfun (a,l) v = (a+v, l+1)

I am under the impression that there has to be an easy way to get rid of the whole avgOf implementation and replace that with a simple one that just 'lifts' avg to work on lenses.

Upvotes: 4

Views: 258

Answers (1)

Edward Kmett
Edward Kmett

Reputation: 29962

You can use partsOf to construct this out of whole cloth.

avgOf l xs = xs^..partsOf l.to avg

Upvotes: 3

Related Questions