5
5

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.

HaskellのreplicateみたいなやつをJavaScriptで実装してみる

Last updated at Posted at 2014-11-02

Haskellの、

replicate 5 5
[5,5,5,5,5]

みたいなのをJavaScriptで書いてみました。
さすがにreplicate 5 5なのは実装出来なかったので、
第二引数は配列にしました。

function replicate(n, x) {
  if (n <= 1) {
    return x;
  } else {
    x.push(x[0]);
    return replicate(n - 1, x);
  }
};
console.log(replicate(5,[5]));

こんな感じ。

追記

頂いたコメントからの改修版です。コメントそのまんまです。

function replicate(n, x) {
    if (n == 0) return [];
    return [x].concat(replicate(n - 1, x));
}

console.log(replicate(5, 5));
5
5
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?