0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python to RubyAdvent Calendar 2021

Day 10

[py2rb] 部分適用

Last updated at Posted at 2022-02-09

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

partial (Python)

from functools import partial

def partial_func(name, value):
    print(name, value)

func1 = partial(partial_func, 'aa')

func1('bb')

# aa bb

ふむふむ。

どうすRuby

lambda.rb
func2 = lambda do |name|
  partial_func = lambda do |value|
    puts "#{name} #{value}"
  end
end

func1 = func2.call('aa')
func1.call('bb')

func2.call('aa').call('bb')

引数を2回に分けて渡すと考えるなら、lambdaでも良さそう。
ありそうなパターン

消費税設定 = lambda do |消費税|
  partial_func = lambda do |税抜き価格|
    puts (税抜き価格 * (1 + 消費税)).floor
  end
end

税込み価格 = 消費税設定.call(0.1)
税込み価格.call(100)
税込み価格.call(109)
税込み価格.call(110)

# output
110
119
121

curry
消費税設定 = lambda do |消費税, 税抜き価格|
  puts (税抜き価格 * (1 + 消費税)).floor
end.curry

税込み価格 = 消費税設定.call(0.1)
税込み価格.call(100)
税込み価格.call(109)
税込み価格.call(110)

curryすると、lambdaを二重にしなくても上手くやってくれる。

class.rb
class A
  def initialize(tax)
    @tax = tax
  end

  def taxin(value)
    puts (value * (1 + @tax)).floor
  end
end

a = A.new(0.1)
a.taxin(100)
a.taxin(109)
a.taxin(110)

まとめると、既存のメソッドを再利用する分には便利ですが、新規で作るならクラスで十分かも。

メモ

  • Python の partial を学習した
  • 百里を行く者は九十里を半ばとす
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?