proc函数相对于方法有什么优点

发布于 2024-11-30 08:41:57 字数 477 浏览 4 评论 0原文

我正在解决 Project Euler 上的一些问题,并且我提到我总是将短方法包装在 proc 函数中。我问自己“为什么?”。答案是“我不知道。也许是因为它很短?”。

那么 proc 函数相对于普通方法除了短之外还有什么优点呢:)

# Proc
is_prime = proc{|number| !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})}

# Ordinary method
def is_prime(number)
  !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})
end

I was solving some problems on Project Euler and I mentioned that I always wrap short methods in proc functions. I asked myself "Why?". The answer was "I don't know. Maybe because it is short?".

So what are the advantages of proc functions to ordinary methods except that they are short :)

# Proc
is_prime = proc{|number| !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})}

# Ordinary method
def is_prime(number)
  !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两人的回忆 2024-12-07 08:41:57

我立即想到的是能够传递它们并将它们存储在数据结构中。我在一个小型命令行解析器中使用后一种情况不太长:使用正则表达式解析用户输入,并使用解析后的字符串的其余部分作为参数调用 commands[command] 。当然,您可以使用方法和发送来执行相同的操作,但恕我直言,命令哈希更好。我有时使用的另一件事——尽管它在 Ruby 中并不常见——是 curry procs,你不能用方法真正做到这一点:

>> multiplier = proc { |x, y| x * y }
=> #<Proc:0x00000100a158f0@(irb):1>
>> times_two = multiplier.curry[2]
=> #<Proc:0x00000100a089c0>
>> times_two[5]
=> 10

编辑:这是另一个例子(简化,没有错误处理):

 commands = { :double => proc { |x| x * 2 }, :half => proc { |x| x / 2 } }
 run_command = proc do 
     command, arg = STDIN.gets.split 
     commands[command.intern][arg.to_i]
 end
 run_command.call
 half 10
 # => 5
 run_command[]
 double 5
 # => 10

Being able to pass them around and to store them in data structures is something that immediately comes to mind. I used the latter case not too long in a small command line parser: parse user input with a regex and call commands[command] with the rest of the parsed string as arguments. Sure, you could do the same with methods and send, but IMHO the commands hash is nicer. Another thing I sometimes use — even though it's not really common in Ruby — is to curry procs, which you can't really do with a method:

>> multiplier = proc { |x, y| x * y }
=> #<Proc:0x00000100a158f0@(irb):1>
>> times_two = multiplier.curry[2]
=> #<Proc:0x00000100a089c0>
>> times_two[5]
=> 10

EDIT: Here's another example (simplified, no error handling):

 commands = { :double => proc { |x| x * 2 }, :half => proc { |x| x / 2 } }
 run_command = proc do 
     command, arg = STDIN.gets.split 
     commands[command.intern][arg.to_i]
 end
 run_command.call
 half 10
 # => 5
 run_command[]
 double 5
 # => 10
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文