Upgrade to Pro — share decks privately, control downloads, hide ads and more …

functionalなアプローチで動的要素を排除する

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 functionalなアプローチで動的要素を排除する

Avatar for Ryoichi SEKIGUCHI

Ryoichi SEKIGUCHI

January 18, 2025
Tweet

More Decks by Ryoichi SEKIGUCHI

Other Decks in Programming

Transcript

  1. 動的なあれこれ types = ["a", 1] types.each do |type| case type

    when String public_send(:method_for_string) when Integer public_send(:method_for_integer) else raise ArgumentError end end
  2. カリー化 f = -> (arg1, arg2) { arg1 + arg2

    }.curry(2).call(1) f.call(2) #=> 3
  3. 関数合成 f1 = -> (arg1, arg2) { arg1 + arg2

    }.curry(2).call(1) f2 = -> (arg3) { arg3.odd? } f = f1 >> f2 f.call(2) #=> true
  4. 少し具体的な例 : 顧客データ import機能 A B C D 1 2

    3 4 元データをサービスDBにimportしたいが 変換が必要なケース
  5. 例1: デフォルト値をセットする処理 DEFAULT_VALUE = "foo" f = -> (default_value, value)

    { value.nil? ? default_value : value }.curry(2).call(DEFAULT_VALUE) f.call(nil) #=> "foo"
  6. 例3: マッピングを行う処理 rule = RULES[:type1][:conversion] f = -> (conversion_rule, value)

    { conversion_rule[value] }.curry(2).call(rule) f.call(“foo”) #=> "hoge"
  7. 例4: 1,2,3全ての処理を行う処理 DEFAULT_VALUE = "foo" f1 = -> (default_value, value)

    { value.empty? ? default_value : value }.curry(2).call(DEFAULT_VALUE)
  8. 例4: 1,2,3全ての処理を行う処理 f1 = -> (default_value, value) { value.nil? ?

    default_value : value }.curry(2).call("foo") f2 = ->(value) { value.upcase } f3 = -> (conversion_rule, value) { conversion_rule[value] }.curry(2).call(rule)