1

Suppose I have the following function

printVariance :: [Float] -> IO ()
printVariance [] = return ()
printVariance (x:xs)
    | x >= avg (x:xs) = print (x - avg (x:xs)) >> printVariance xs
    | otherwise       = printVariance xs

Which gets a list, checks which elements are bigger than the average and prints their value - avg.

My problem is that the avg value changes every step. How can I define it just once and use its value for the recursion?

1
  • 2
    You might want to rewrite this using folds and maps instead of recursing directly. This would allow you to attach a where or a let binding where you'd define your avg as something along the lines of (foldr (+) 0 xs) / length xs. Commented Feb 5, 2017 at 17:01

1 Answer 1

6

Move the recursion into a helper function. That function can either take the average as a parameter or you could define locally to printVariance and define another local variable holding the average, which the function could then access.

In code:

printVariance :: [Float] -> IO ()
printVariance xs = loop xs
  where
    average = avg xs
    loop [] = return ()
    loop (x:xs)
      | x >= average = print (x - average) >> loop xs
      | otherwise = loop xs

PS: It would be good design to separate the IO from the program logic. So I'd recommend you make your function simply produce a list of the values you want, rather than printing them and move the IO into a separate function (or just main).

PPS: You're not really calculating the variance, so I'd recommend naming the function something else.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, we've written the same program. I'll delete my answer for brevity's sake :)
You nailed it, I don't know how I could not think it, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.