Posts Tagged ‘Computation’

Scott Hanselman has been posting weekly snippets of code in various languages … today he did Fibonacci sequences … by the way, the point of his posts is to get you to read code in other languages, not necessarily showing the best way to do things in any of the languages represented — you only solve fibonacci sequences recursively in demos, not in real life. Well, except perhaps in tightly optimized tail-recursion languages, maybe in Haskell …

In C#


int fib(int x) { return (x<2) ? 1 :fib(x-1) + fib(x-2) }
fib(20);

In PowerShell


filter fib{ if($_-lt2){1}else{($_-1|fib)+($_-2|fib)}}
20 | fib

That’s just beautiful ;) ... incidentally, by default, PowerShell will only recurse up to 100 levels in the stack, so it kind-of sucks at recursive calls. You could also write that as a traditional function in powershell, but the way powershell passes arguments to functions makes it really awkward. I’ll put it on multiple lines so you can read it easier.


function fib($i){
  if($i -lt 2) {
    1
  }else{
    # yes, every one of these parentheses is required
    (fib ($i-1)) + (fib ($i-2))
  }
}

fib 20

As a side note, that function actually runs measurably slower than the pipeline method … but speeds up noticeably if you stick a few [int] type specifiers in the right places so PowerShell doesn’t have to infer types — something to think about.

Search My Content