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

色んな言語でカウンター

Last updated at Posted at 2019-04-02

色んな言語でカウンター

色んな言語でカウンターを作ります。

Python

関数版

関数の外のスコープを参照するためにnonlocal宣言します。

def counter(): 
    x = 0 
    def _count(): 
        nonlocal x 
        x += 1 
        return x 
    return _count 
count = counter()                                              
count()                                                        
1
count()                                                        
2

クラス版

class Counter(): 
    def __init__(self): 
        self.x = 0 
    def counter(self): 
        self.x += 1 
        return self.x 

count = Counter() 
1
count = Counter() 
2
count = Counter() 
3

JavaScript

ES5

即時関数を使います。count()を実行する度に、即時関数内の_counter()が実行されて、xの値が加算されます。

const count = (function(){
    let x = 0;
    function _counter(){
        return ++x;
    }
    return _counter})()
count()
1
count()
2

ES6

ジェネレータを使います。

function* counter() {
    let count = 0;
    while(true) {
      yield ++count;
    }
}

const count = counter();
count.next().value;
1
count.next().value;
2
count.next().value;
3

node.js

イベントを使います。

const EventEmitter = require('events');
class Emitter extends EventEmitter{};
const emitter = new Emitter()
let counter = 0
emitter.on('count', ()=>{console.log(++counter)})
function countEvent(){emitter.emit('count')}

countEvent()
1
countEvent()
2
countEvent()
3

Common Lisp

funcallを使います。

(defun counter()
    (let((x 0))
            (lambda()(incf x))))

(defvar *count* (counter))
* (funcall *count*)
1
* (funcall *count*)
2
* (funcall *count*)
3

Scheme

レキシカルスコープでラップしています。

(define counter
   (let ((x 0))
     (lambda ()
         (set! x (+ x 1))
         x)))
(counter)
1
(counter)
2
(counter)
3

Clojure

状態管理は atom 等で切り離すのが Clojure 流のようです。

(def counter (atom 0))

(defn next-value []
  (swap! counter inc))
user=> (next-value)
1
user=> (next-value)
2
user=> (next-value)
3

Ruby

class Counter
   def initialize
     @x = 0
   end
   def counter
     @x += 1
   end
end

count = Counter.new
count.counter()
1
count.counter()
2
count.counter()
3

Java


C


C++


C Sharp


Haskell


Ocaml


Scala


Go


Perl


思いつく言語でカウンターを書いてみました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?