109
\$\begingroup\$

As of 13/03/2018 16:45 UTC, the winner is answer #345, by Khuldraeseth na'Barya. This means the contest is officially over, but feel free to continue posting answers, just so long as they follow the rules.

As well, just a quick shout out to the top three answerers in terms of numbers of answers:

1. NieDzejkob - 41 answers

2. KSmarts - 30 answers

3. Hyper Neutrino - 26 answers


This is an answer chaining question that uses sequences from OEIS, and the length of the previous submission.

This answer chaining question will work in the following way:

  • I will post the first answer. All other solutions must stem from that.
  • The next user (let's call them userA) will find the OEIS sequence in which its index number (see below) is the same as the length of my code.
  • Using the sequence, they must then code, in an unused language, a program that takes an integer as input, n, and outputs the nth number in that sequence.
  • Next, they post their solution after mine, and a new user (userB) must repeat the same thing.

The nth term of a sequence is the term n times after the first, working with the first value being the first value given on its OEIS page. In this question, we will use 0-indexing for these sequences. For example, with A000242 and n = 3, the correct result would be 25.

However!

This is not a , so shortest code doesn't matter. But the length of your code does still have an impact. To prevent the duplication of sequences, your bytecount must be unique. This means that no other program submitted here can be the same length in bytes as yours.

If there isn't a sequence for then length of the last post, then the sequence for your post is the lowest unused sequence. This means that the sequences used also have to be unique, and that the sequence cannot be the same as your bytecount.

After an answer has been posted and no new answers have been posted for more than a week, the answer before the last posted (the one who didn't break the chain) will win.

Input and Output

Generic input and output rules apply. Input must be an integer or a string representation of an integer and output must be the correct value in the sequence.

Formatting

As with most questions, please format your answer like this

# N. language, length, [sequence](link)

`code`

[next sequence](link)

*anything else*

Rules

  • You must wait for at least 1 hour before posting an answer, after having posted.
  • You may not post twice (or more) in a row.
  • The index number of a sequence is the number after the A part, and with leading zeros removed (e.g. for A000040 the index number is 40)
  • You can assume that neither the input nor the required output will be outside your languages numerical range, but please don't abuse this by choosing a language that can only use the number 1, for example.
  • If the length of your submission is greater than 65536 characters long, please provide a link to a way to access the code (pastebin for example).
  • n will never be larger than 1000, or be out of bounds for the sequence, simply to prevent accuracy discrepancies from stopping a language from competing.
  • Every 150 (valid) answers, the number of times a language may be used increases. So after 150 solutions have been posted, every language may be used twice (with all previous answers counting towards this). For instance, when 150 answers have been posted, Python 3 may be used twice, but due to the fact that it has already been used once, this means it can only be used once more until 300 answers have been posted.
  • Please be helpful and post a link to the next sequence to be used. This isn't required, but is a recommendation.
  • Different versions of languages, e.g. Python 2 and Python 3 are different languages. As a general rule, if the different versions are both available on Try It Online, they are different languages, but keep in mind that this is a general rule and not a rigid answer.
  • It is not banned, but please try not to copy the code from the OEIS page, and actually try to solve it.
  • Hardcoding is only allowed if the sequence is finite. Please note that the answer that prompted this (#40) is the exception to the rule. A few answers early in the chain hardcode, but these can be ignored, as there is no good in deleting the chain up to, say, #100.

Answer chain snippet

var QUESTION_ID=133754,OVERRIDE_USER=66833;function shareUrl(i){return"https://codegolf.stackexchange.com/a/"+i}function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getTemplate(s){return jQuery(jQuery("#answer-template").html().replace("{{PLACE}}",s.index+".").replace("{{NAME}}",s.user).replace("{{LANGUAGE}}",s.language).replace("{{SEQUENCE}}",s.sequence).replace("{{SIZE}}",s.size).replace("{{LINK}}",s.link))}function search(l,q){m=jQuery("<tbody id='answers'></tbody>");e.forEach(function(s){if(!q||(l==0&&RegExp('^'+q,'i').exec(s.lang_name))||(l==1&&q===''+s.size)){m.append(jQuery(getTemplate(s)))}});jQuery("#answers").remove();jQuery(".answer-list").append(m)}function sortby(ix){t=document.querySelector('#answers');_els=t.querySelectorAll('tr');els=[];for(var i=0;i<_els.length;i++){els.push(_els[i]);}els.sortBy(function(a){a=a.cells[ix].innerText;return ix==0||ix==4?Number(a):a.toLowerCase()});for(var i=0;i<els.length;i++)t.appendChild(els[i]);}function checkSize(x){if(!x)return jQuery("#size-used").text("");var i=b.indexOf(+x);if(i<0)return jQuery("#size-used").text("Available!");var low=+x,high=+x;while(~b.indexOf(low))low--;while(~b.indexOf(high))high++;jQuery("#size-used").text(("Not available. The nearest are "+low+" and "+high).replace("are 0 and","is"))}function checkLang(x){}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.answer_id;answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return (e.owner.user_id==OVERRIDE_USER?"<span id='question-author'>"+e.owner.display_name+"</span>":e.owner.display_name)}function process(){b=[];c=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);if(a){e.push({user:getAuthorName(s),size:+a[4],language:a[2],lang_name:a[3],index:+a[1],sequence:a[5],link:shareUrl(s.answer_id)});if(b.indexOf(+a[4])>=0&&c.indexOf(+a[4])<0){c.push(+a[4])};b.push(+a[4])}else{jQuery('#weird-answers').append('<a href="'+shareUrl(s.answer_id)+'">This answer</a> is not formatted correctly. <b>Do not trust the information provided by this snippet until this message disappears.</b><br />')}}),e.sortBy(function(e){return e.index});e.forEach(function(e){jQuery("#answers").append(getTemplate(e))});var q="A"+("000000"+e.slice(-1)[0].size).slice(-6);jQuery("#next").html("<a href='http://oeis.org/"+q+"'>"+q+"</a>");c.forEach(function(n){jQuery('#weird-answers').append('The bytecount '+n+' was used more than once!<br />')})}Array.prototype.sortBy=function(f){return this.sort(function(a,b){if(f)a=f(a),b=f(b);return(a>b)-(a<b)})};var ANSWER_FILTER="!*RB.h_b*K(IAWbmRBLe",COMMENT_FILTER="!owfmI7e3fd9oB",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page,e=[];getAnswers();var SCORE_REG=/<h\d>\s*(\d+)\.\s*((?:<a [^>]+>\s*)?((?:[^\n,](?!<\/a>))*[^\s,])(?:<\/a>)?),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*, ((?:<a[^>]+>\s*)?A\d+(?:\s*<\/a>)?)\s*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important;font-family:Roboto,sans-serif}#answer-list,#language-list{padding:10px;/*width:290px*/;float:left;display:flex;flex-wrap:wrap;list-style:none;}table thead{font-weight:700}table td{padding:5px}ul{margin:0px}#board{display:flex;flex-direction:column;}#language-list li{padding:2px 5px;}#langs-tit{margin-bottom:5px}#byte-counts{display:block;margin-left:15px;}#question-author{color:purple;text-shadow: 0 0 15px rgba(128,0,128,0.1);}#label-info{font-weight: normal;font-size: 14px;font-style: italic;color: dimgray;padding-left: 10px;vertical-align: middle; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><p id="weird-answers"></p><p>Currently waiting on <span id="next"></span></p><span>Search by Byte Count: <input id="search" type="number" min=1 oninput="checkSize(this.value);search(1,this.value)" onclick="document.getElementById('search2').value='';!this.value&&search(0,'')"/> <span id="size-used"></span></span><br><span>Search by Language: <input id="search2" oninput="checkLang(this.value);search(0,this.value)" onclick="document.getElementById('search').value='';!this.value&&search(0,'')"/> <span id="language-used"></span></span><h2>Answer chain <span id="label-info">click a label to sort by column</span></h2><table class="answer-list"><thead><tr><td  onclick="sortby(0)">#</td><td onclick="sortby(1)">Author</td><td onclick="sortby(2)">Language</td><td onclick="sortby(3)">Sequence</td><td onclick="sortby(4)">Size</td></tr></thead><tbody id="answers"></tbody></table><table style="display: none"><tbody id="answer-template"><tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"><tbody id="language-template"><tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>

\$\endgroup\$
13
  • \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$
    – Dennis
    Oct 31, 2017 at 2:49
  • \$\begingroup\$ Is it OK if a program would need a better floating-point accuracy for the builtin float/double type in order to produce values for larger n? \$\endgroup\$
    – Maya
    Nov 21, 2017 at 15:15
  • 1
    \$\begingroup\$ @Giuseppe No, as you're generating the numbers by doing the maths, rather than just placing them into an array/string \$\endgroup\$ Dec 15, 2017 at 22:14
  • 2
    \$\begingroup\$ @cairdcoinheringaahing In my opinion that's hardcoding the gamma constant. It doesn't work "in theory" for larger numbers. \$\endgroup\$
    – DELETE_ME
    Dec 22, 2017 at 12:44
  • 6
    \$\begingroup\$ Chat room \$\endgroup\$
    – DELETE_ME
    Dec 22, 2017 at 12:45

406 Answers 406

1
10 11 12 13
14
1
\$\begingroup\$

385. Vyxal, 182 bytes, A000798

ɾṗꜝṗ'fUL?=;'2↔:ƛfUs;$ƛƒ↔Us;ꜝ∪$F¬;L
############################
#############################
#############################
#############################
############################

Try it Online!

Next sequence.

\$\endgroup\$
1
\$\begingroup\$

386. Zig, 350 bytes, A000182

fn a000182(comptime n: comptime_int) [n]i64 {
    var s = [_]i64{0} ** n;

    s[0] = 1;

    for (s[1..]) |*a, i| {
        a.* = @intCast(i64, i + 1) * s[i];
    }

    for (s[1..]) |_, i| {
        for (s[i + 1 ..]) |*a, j| {
            a.* *= @intCast(i64, j + 2);
            a.* += @intCast(i64, j) * s[i + j];
        }
    }

    return s;
}

Attempt This Online!

Next sequence!

Uses the Zig language because the sequence is called the Zag numbers.

\$\endgroup\$
1
\$\begingroup\$

387. Cognate, 1984 bytes, A000350

~~ First some helper words to make the prose flow like water.

Def Equal as (==);
Def Zero as (Equal to 0);
Def Positive to be (> 0);
Def Sum as (+);
Def Less as (- 1);
Def Last as (Modulo 10);
Def Quotient as (Floor /);
Def Mutable as (Box);
Def Value as (Unbox);

~~ Now we are ready to rumble.

Def Fibonacci as (
   Let N be the term we wish to find;
   Let A be a Mutable value of 0;
   Let B be a Mutable value of 1;
   do the following (
      put the Value of B aside for now;
      Set B to the Sum of the Value of A and the Value of B;
      A; should now be Set to the old value of b we put aside;
   ); N; Times;
   return the Value of A
);

Def Increment as (
   Let N be a mutable variable containing the input;
   Set N to the Sum of 1 and the Value of N
)

Def Chop as (
   Let N be a mutable variable containing the input;
   Set N to the Quotient of 10 and the Value of N;
);

Def End as (
   Let A be the first Integer!;
   Let B be the second Integer!;
   return whether the Last digit of A; and the Last digit of B; are Equal
);

~~ This is a function that determines whether its input is a member of OEIS: A000350.
Def Ends as (
   Let N be a Mutable variable containing the input;
   Let K be a Mutable variable containing the Fibonacci Value of N;
   While (the Value of N; is Positive; and the Value of N and the Value of K; End with the same digit; are Both true) (
      Chop the last digit off N;
      Chop the last digit off K;
   );
   return whether the Value of N; is Zero
);

Def A000350 as (
   Let N be the term of the sequence we want to find;
   Let K be the Mutable number of terms we've found starting with 0;
   Let M be a Mutable number to test for membership starting with 0;
   Until (the Value of K; and N; are Equal) do the following (
      Do either of the following-
      If the mth fibonacci number Ends with the Value of M then (Increment K) otherwise (do nothing);
      Increment M;
   );
   return one Less than the Value of M
);

Attempt This Online!

Cognate is a new stack language that is unique in that it reads right to left (superficially giving it the appearance of Polish notation). But using the ; word, you can ; make ; it ; read ; left ; to ; right. Having such fine-grained control over the flow of data makes it really easy to take advantage of Cognate's seamless comments (anything lowercase) to make things sound like English.

Mind you, this is incredibly overwrought -- you should probably never go this far with the natural language stuff -- but I got addicted to making it sound like English and wanted to see how far I could push it.

Next sequence!

\$\endgroup\$
4
  • \$\begingroup\$ Da hell is that next sequence lol \$\endgroup\$
    – Aiden Chow
    Aug 21, 2022 at 2:34
  • \$\begingroup\$ @AidenChow I'm guessing whoever decides to tackle it should do oeis.org/A045535 instead. \$\endgroup\$
    – chunes
    Aug 21, 2022 at 2:47
  • \$\begingroup\$ @AidenChow I think erroneous sequences can be hardcoded: codegolf.stackexchange.com/a/156507/9288 \$\endgroup\$
    – alephalpha
    Aug 23, 2022 at 12:15
  • \$\begingroup\$ @alephalpha Huh that's interesting, I suppose that makes sense. \$\endgroup\$
    – Aiden Chow
    Aug 24, 2022 at 5:05
1
\$\begingroup\$

389. ReScript, 1001 bytes, A000192

type rec expr =
  | Const(int)
  | X
  | Cos(expr)
  | Sin(expr)
  | Add(expr, expr)
  | Mul(expr, expr)
  | Div(expr, expr)

let rec eval_at_0 = (e: expr): int =>
  switch e {
  | Const(c) => c
  | X => 0
  | Cos(_) => 1
  | Sin(_) => 0
  | Add(e, f) => eval_at_0(e) + eval_at_0(f)
  | Mul(e, f) => eval_at_0(e) * eval_at_0(f)
  | Div(e, f) => eval_at_0(e) / eval_at_0(f)
  }

let rec deriv = (e: expr): expr =>
  switch e {
  | Const(_) => Const(0)
  | X => Const(1)
  | Cos(e) => Mul(Const(-1), Mul(deriv(e), Sin(e)))
  | Sin(e) => Mul(deriv(e), Cos(e))
  | Add(e, f) => Add(deriv(e), deriv(f))
  | Mul(e, f) => Add(Mul(deriv(e), f), Mul(e, deriv(f)))
  | Div(e, f) =>
    Div(Add(Mul(deriv(e), f), Mul(Const(-1), Mul(e, deriv(f)))), Mul(f, f))
  }

let rec iter = (f, a, n: int) => n > 0 ? f(iter(f, a, n - 1)) : a

let egf: expr = Div(
  Mul(Const(2), Cos(Mul(Const(3), X))),
  Add(Mul(Const(2), Cos(Mul(Const(4), X))), Const(-1)),
)

let a000192 = (n: int) => eval_at_0(iter(deriv, egf, 2 * n))

Try it online!

Next sequence!

The exponential generating function of the sequence is \$2\cos(3x)/(2\cos(4x)-1)\$. Here I compute the sequence using symbolic differentiation. Very inefficient.

ReScript is a rebranding and cleanup of Reason, so I can reuse the Reason code for A000187 with some small modification.

\$\endgroup\$
1
\$\begingroup\$

393. Red, 181 bytes, A000212

Red[
    title: "OEIS A000212"
    author: "chunes"
    date: 2022-08-29
    tabs: 4
    version: 0.6.4
    company: ""
    rights: "nein"
]

f: func[n][to 1 round/down(n ** 2 / 3)]

Try it online!

Next sequence!

\$\endgroup\$
1
\$\begingroup\$

391. Egison, 374 bytes, A000191

-- The egf (exponential generating function) of the sequence
def egf := 2 * sin t / (2 * cos (2 * t) - 1)

-- Repeatedly applies the differential operator to the egf, and substitutes t with 0
def a000191List := map (substitute [ (t,0) ]) $ iterate (flip d/d t) egf

-- Takes the 2 * (n + 1)'th term, because Egison is 1-indexed
def a000191 n := nth (2 * (n + 1)) a000191List

Try it online!

Next sequence!

The exponential generating function of the sequence is \$2\sin(t)/(2\cos(2t)-1)\$. Here I use symbolic differentiation again, but using Egison's built-in d/d function. Still very inefficient.

Egison is a functional programming language featuring its expressive pattern-matching facility. It can also be used as a Computer Algebra System.

\$\endgroup\$
1
\$\begingroup\$

394. kalker, 248 bytes, A000181

f(n) = Σ(i = 0, n, (-1)^i (n + 4) (n - i)! (2 n + 3 - i)! / (12 i! (2 n - 2 i)!))
f(n) = Σ(i = 0, n, (-1)^i (n + 4) (n - i)! (2 n + 3 - i)! / (12 i! (2 n - 2 i)!))
f(n) = Σ(i = 0, n, (-1)^i (n + 4) (n - i)! (2 n + 3 - i)! / (12 i! (2 n - 2 i)!))

Try it online!

Next sequence!

Kalker is a scientific calculator that supports math-like syntax with user-defined variables, functions, derivation, integration, and complex numbers.

Since writing the definition once is too short, I write it three times.

\$\endgroup\$
1
\$\begingroup\$

395. Knight, 424 bytes, A000248

; = factorial BLOCK
    IF (< num 2)
        1
        (* num (; (= num (- num 1)) (CALL factorial)))
; = choose BLOCK
    ; = num n
    ; = numerator (CALL factorial)
    ; = num k
    ; = den (CALL factorial)
    ; = num (- n k)
    ; = den (* den (CALL factorial))
    : / numerator den
; = n (EVAL PROMPT)
; = k 0
; = s 0
; WHILE (< k (+ 1 n))
    ; = s (+ s (* (CALL choose) (^ (- n k) k)))
    : = k (+ 1 k)
: OUTPUT s

Try it online!

Next sequence!

\$\endgroup\$
1
\$\begingroup\$

401. HOPS, 303 bytes, A000314

exponential_generating_function_of_a035351 = x * exp((2 * exponential_generating_function_of_a035351 - exponential_generating_function_of_a035351 ^ 2) / (2 - 2 * exponential_generating_function_of_a035351));  a035351 = laplace(exponential_generating_function_of_a035351);  a000314 = 1 + int(a035351 / x)

Next sequence!

Attempt This Online!

Or 36 bytes: a=x*exp((a+a/(1-a))/2);1+a.*{(n-1)!}.

\$\endgroup\$
1
\$\begingroup\$

403. Quipu, 234 bytes, A000254

" 0&  1&  2&  3&  4& "
"--------------------"
  \/  1&  1&  1&  2&
  1&  ++  []  ++  []
  ++  0&  **  1&  /\
      []  3&  []    
      %%  []  **    
      4&  ++  1&    
      ==  1&  --    
          ++  1&    
              ??    

Next sequence!

Attempt This Online!

\$\endgroup\$
1
  • \$\begingroup\$ Lol what kind of lang is this \$\endgroup\$
    – Aiden Chow
    Sep 10, 2022 at 6:48
1
\$\begingroup\$

404. Raku, 309 bytes, A000234

sub a($i, $m, $k) {
  if ($k == 1) {
    return 1;
  }
  my $s = 0;
  my $l = floor($m ** (3 / 2));
  for 1..min($l, $i) -> $j {
    my $m2 = $m - $j ** (2 / 3);
    if ($m2.floor >= 1) {
      $s += a($j, $m2, $k-1);
    }
    $s += 1;
  }
  return $s;
}

my $n = get;

print a(floor($n ** (3 / 2)), $n, $n);

Try it online!

Next sequence!

\$\endgroup\$
1
\$\begingroup\$

366. HOPS, 202 bytes, A000207

catalan_numbers = 1 + x * catalan_numbers ^ 2;   a000207 = (1 - 12 * x - (1 - 4 * x) * catalan_numbers(x) + 3 * x * (3 + 2 * x) * catalan_numbers(x ^ 2) + 4 * x ^ 2 * catalan_numbers(x ^ 3)) / (12 * x)

Next sequence!

Attempt This Online!

HOPS is an extremely powerful language for sequences: you input the generating function, it outputs the sequence. You can even define the generating function using recursion.

\$\endgroup\$
1
\$\begingroup\$

406. Symja, 198 bytes, A000175

(* Based on Herman Jamke's second PARI/GP code on OEIS *)
A000175(n_) := 2 ^ (2 * n - 1) * Product(k ^ Floor(n / k), {k, 1, n}) * SeriesCoefficient(BesselJ(1, x) / BesselJ(0, x), {x, 0, 2 * n - 1});

Next sequence!

Try It Online!

Symja is a Java Symbolic Math System. Its syntax is basically the same as Mathematica, except it uses round brackets instead of square ones.

\$\endgroup\$
0
\$\begingroup\$

355. Pyret, 244 bytes, A000195

fun a000195(n :: NumNonNegative) -> NumInteger:
  num-floor(num-log(n))
where:
  a000195(1) is 0
  a000195(2) is 0
  a000195(3) is 1
  a000195(4) is 1
  a000195(5) is 1
  a000195(6) is 1
  a000195(7) is 1
  a000195(8) is 2
  a000195(9) is 2
end

Next sequence!

Try it online!

One interesting feature of this language is that you can add unit tests to functions using the where clause.

\$\endgroup\$
0
\$\begingroup\$

358. CoffeeScript 2, 304 bytes, A000167

# BesselK satisfies the following recurrence relation: 
# BesselK(n + 1, x) = BesselK(n - 1, x) + n * BesselK(n, x)

b = [0.11389387274953344, 0.13986588181652243]

besselk2 = (n) ->
  while b.length <= n
    i = b.length - 1
    b.push(b[i - 1] + i * b[i])
  b[n]

a000167 = (n) -> Math.round besselk2 n

Try it online!

Next sequence!

This sequence grows very fast. Only the first 20 outputs are accurate. But CoffeeScript doesn't have an Integer type anyway. Its number type is 64-bit floating-points. So I think some inaccuracy is allowed.

\$\endgroup\$
0
\$\begingroup\$

384. Clean, 798 bytes, A001002

import StdEnv

:: Series a = (:+) infixr 6 a (Series a)

coeff :: Int (Series a) -> a
coeff 0 (a :+ _ ) = a
coeff n (_ :+ as) = coeff (n - 1) as

truncate :: Int (Series a) -> [a]
truncate 0 _         = []
truncate n (a :+ as) = [a : truncate (n - 1) as]

instance zero (Series a) | zero a where
    zero = zero :+ zero

instance one (Series a) | one a & zero a where
    one = one :+ zero

instance + (Series a) | + a where
    (+) (a :+ as) (b :+ bs) = (a + b) :+ (as + bs)

instance * (Series a) | + a & * a where
    (*) (a :+ as) (b :+ bs) = (a * b) :+ (as * (b :+ bs) + a ** bs)

(**) :: a (Series a) -> Series a | * a
(**) a (b :+ bs) = a * b :+ a ** bs

x :: Series a | one a & zero a
x = zero :+ one :+ zero

A001002 :: Series Int
A001002 = one :+ (A001002 * A001002 * (one + x * A001002))

Try it online!

Next sequence!

Its generating function satisfies \$A = 1 + x A^2 + x^2 A^3\$.

Clean is very similar to Haskell: purely functional, lazy, currying, operator overloading with type classes. So I can borrow this Haskell implementation of formal power series.

\$\endgroup\$
1
10 11 12 13
14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.