Avoid temporary variables using name shading

I create many temporary variables in Haskell:

main = do let nums'' = [1..10] let nums' = a . bunch . of_ . functions $ nums'' let nums = another . bunch . of_ . functions $ nums' print nums 

That is, I do not want to write a long chain of such functions:

 let nums = another . bunch . of_ . functions . a . bunch . of_ . functions $ [1..10] 

Because it becomes unreadable to me, so I try to group functions according to what they do. In this process, I create a bunch of ugly temporary variables like nums'' and nums' (I could give them more meaningful names, but the dot still stands ... every new line means a new variable). This is the case where a shaded variable will lead to cleaner code. I would like to do something like:

 let nums = [1..10] nums = a . bunch . of_ . functions $ nums nums = another . bunch . of_ . functions $ nums 

those. exactly the same as above, but without temporary variables. Is there a way to do this in Haskell? Perhaps all of this can be wrapped in a "transaction":

 atomically $ do (...this code...) return nums 

Something that would let Haskell know that the code in this section contains shaded variables, and he should only worry about the end result. Is it possible?

+6
source share
4 answers

This style is very common:

 let nums = another . bunch . of_ . functions . a . bunch . of_ . functions $ [1..10] 

It clearly defines the code; a . Serves as a temporary variable name.

And he avoids the dangerous problems that can arise when you start to obscure variable names - accidentally accessing the wrong x will sooner or later lead you into trouble.

+11
source

Here is a sentence that no one has yet given, which I use from time to time: you can name your functions and not name your values! For example, perhaps you can write:

 let runningSum = a . bunch . of_ . functions weight = another . bunch . of_ . functions in weight . runningSum $ [1..10] 
+7
source

Since your names ( nums , nums' , nums'' , ...) do not contain grouping information, you can simply use line breaks to group functions and pass the same thing:

 main = let nums = a . bunch . of_ . functions . another . bunch . of_ . functions $ [1..10] in print nums 

However, I would suggest that instead you give the names of the subcomputations that convey the information, for example. normalizedNums , average , etc. Then there is no ugly problem with shading because you use different names.

+6
source

If absolutely necessary for you, this is possible, but not idiomatic. Use what don or luqui offers.

 main = do nums <- return [1..10] nums <- return $ a . bunch . of_ . functions $ nums nums <- return $ another . bunch . of_ . functions $ nums print nums 

If you are not in a monad, you can always start a new do block in an identity monad.

+4
source

Source: https://habr.com/ru/post/916028/


All Articles