6
6

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 5 years have passed since last update.

[Swift]2項演算子をオブジェクトに閉じ込めて遊んでみた

Posted at

2項演算子を閉じ込めるクラス

Operator2.swift
class Operator2<T, U, V>{

    private let f: (T, U) -> V
    
    // 2項演算子で初期化できるか試してみる。
    init(f:(T, U) -> V){
        self.f = f
    }
    
    subscript(arg1: T) -> (U -> V) {
        get {
            return { (arg2: U) -> V in
                return self.f(arg1, arg2)
            }
        }
    }
    
    subscript(arg1: T, arg2: U) -> V {
        get {
            return f(arg1, arg2)
        }
    }
}

テスト

main.swift
let f: Operator2<Int, Int, Int> = Operator2(+) // '+'演算子で初期化
println(f[3, 7]) // subscriptを使って配列っぽく引数を渡すのはご愛嬌
        
let f2: Operator2<Double, Double, Double> = Operator2(*) // 今度はかけ算
let f3 = f2[3.14] // 3.14を掛ける関数を得る。
println(f3(2))    // f3はsubscriptと無関係なので普通の括弧で呼び出す。
println(f3(3))
println(f3(4))

一見うさんくさいコードだけど動きます。

感想

subscriptを使うと、わりと関数呼び出しっぽくなる気がする…。

subscript使いまくってすべての関数をカリー化して、[]が関数呼び出しなのか配列の参照なのかわからないぐらいに…とか妄想(…実際にやるとは言わない)。

6
6
0

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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?