quiz. write a function recurseList(f,x,n) that returst a list, [f(x), f(f(x)), ...], length n.

1    01 Nov 2017 05:17 by u/plankO

write in your fav lang. haskell, javascript, golang

10 comments

2

C++:

#include <iostream>
#include <vector>
int example(int i){
    return i+i;
}
template<typename T> std::vector<T> recurseList(T (*f)(T),T x,size_t n)
{
    if(f == NULL)
        return std::vector<T>(); //TODO:Add better error handling
    std::vector<T> V(n);
    V[0] = f(x);
    for(size_t i = 1; i < n; i++)
        V[i] = f(V[i-1]);
    return V;
}
int main() {
    for(auto &i: recurseList(example,3,5)) {
        std::cout << i << " ";
    }
}
0

nice

2

XQuery:

declare function recurseList($f, $x, $n) {
   let $fx := $f($x) return
   if ($n = 1) then $fx 
   else ($fx, recurseList($f, $fx, $n - 1))
}
0

Bit new to all of this, can I get a bit more info on the input and output this function needs to provide.

0

If I was at home and had the time to waste, I would do this in the warcraft 3 world editor.

0

Perl 5:

sub recurse_list ($f, $x, $n) { 
    map { $x = $f->($x) } 1 .. $n
}

example:

#! /usr/bin/perl
sub recurse_list ($f, $x, $n) { 
    map { $x = $f->($x) } 1 .. $n
}
say join ', ', map $_->[1], 
    recurse_list
        sub ($x) {
            [ $x->[1], $x->[0] + $x->[1] ]
        },
        [1, 1], 5;

outputs:

2, 3, 5, 8, 13
0

Not familiar with Perl but that looks to me like your recurseList function is just mapping the result of a function onto a list. So if you used a doubler function it would return (for n = 5): 2, 4, 6, 8, 10 - which is incorrect.

0

$x is mutated: it receives the previous call's result and becomes the next call's argument.

say join ', ', recurse_list sub ($x) { $x * 2 }, 1, 5;

outputs:

2, 4, 8, 16, 32
0
List<T> RecurseList<T>(Func<T, T> f, T x, int n)
{
     List<T> result = new List<T>();
     for (int i = 0; i < n; i++)
         result.Add(i == 0 ? f(x) : f(result[i - 1]));
     return result;
}

Sample usage:

> Func<int, int> doubler = (input) => input * 2;
> doubler(2)
4
> RecurseList(doubler, 1, 10)
List<int>(10) { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 }
0

TIL, how to con others into doing my coding take home tests.