通过使用名称遮蔽避免临时变量 [英] Avoid temporary variables by using name shadowing

查看:423
本文介绍了通过使用名称遮蔽避免临时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  main = do 
let nums''= [ 1..10]
让nums'= a。一群。 of_。函数$ nums''
让nums = another。一群。 of_。函数$ nums'
print nums

也就是说,我不想写一个如此长的功能链:

  let nums = another。一群。 of_。功能 。一个 。一群。 of_。函数$ [1..10] 

因为它对我来说变得不可读,所以我尝试将根据他们的功能来运作。在这个过程中,我最终创建了一堆丑陋的临时变量,如 nums'' nums'他们更有意义的名字,但这一点仍然存在......每一条新线都意味着一个新变量)。
这是一个阴影变量会导致代码更清晰的情况。我想这样做:

  let nums = [1..10] 
nums = a。一群。 of_。函数$ nums
nums = another。一群。 of_。函数$ nums

I。与上面完全一样,但没有临时变量。 Haskell有没有办法做到这一点?也许整个事情可能被包裹在一个交易中:

 原子地$ do 
(...此代码...)
返回nums

有些东西会让Haskell知道这个代码部分包含阴影变量,它应该只关心最终结果。这是可能的吗?

解决方案

这种风格很常见:

  let nums = another 
。一束
。 of_
。功能
。 a
。一束
。 of_
。函数
$ [1..10]

它清楚地描述了代码;而用作临时变量名称的位置。



它避免了您可能发生的危险问题启动阴影变量名称 - 意外地引用错误的 x 会迟早让你陷入麻烦。


I create a lot of 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 don't want to write a long chain of functions like so:

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

Because it becomes unreadable to me, so I try to group the functions according to what they do. In the process I end up creating a bunch of ugly temporary variables like nums'' and nums' (I could give them more meaningful names, but the point still stands...every new line means a new variable). This is a case where a shadowed variable would result in cleaner code. I'd like to do something like:

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

I.e. exactly the same as above but without the temporary variables. Is there any way to do this in Haskell? Maybe the whole thing could be wrapped in a "transaction":

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

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

解决方案

This style is very common:

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

It clearly delineates the code; while . serves the place of the temporary variable name.

And it avoids the dangerous issues that can happen when you start shadowing variable names -- accidentally referring to the wrong x will get you into trouble sooner or later.

这篇关于通过使用名称遮蔽避免临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆