LoginSignup
0
0

More than 1 year has passed since last update.

JSのmapをSICP風に実装してみた。

Last updated at Posted at 2022-08-07

SICPのmap

(define (map f list)
    (if (null? list)
        '()
        (cons (f (car list)) (map f (cdr list)))
    )
)

実行結果

(print (map (lambda(x) (* x x)) (list 1 2 3 4)))
            // -> (1 4 9 16)
(print (map (lambda(x) (* x 3)) (list 1 2 3 4)))
            // -> (3 6 9 12)

オレオレmap in js

同じように再帰で書くためにSchemeのlist構造にいったんして、最終的な出力をArrayにして戻した。

MyArray([1,2,3,4]).mapなどのように使う。

class MyArray {
    cons;

    constructor(arr) {
        this.cons = this.toCons(arr)
    }

    toCons(arr) {
        if(arr.length === 0) {
            return []
        }else {
            return [arr[0], this.toCons(arr.slice(1))]
        }
    }

    toArray(cons) {
        if(cons.length === 0) {
            return [];
        } else {
            return [cons[0], ...this.toArray(cons[1])]
        }
    }

    myMap(f, cons) {
        if(cons.length === 0) {
            return []
        }else {
            return [f(cons[0]), this.myMap(f, cons[1])]
        }
    }

    map(f) {
        return this.toArray(this.myMap(f, this.cons));
    }
}


const myArr = new MyArray([1,2,3,4]);

console.log(myArr.map((x)=> x*x)); // -> [ 1, 4, 9, 16 ]

実際のmapの実装とどう違うのかはわからない。

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