Friday, June 30, 2006

one line fibonacci

I've been playing with windows powershell (aka monad, aka MSH) recently. It's got some really great functional programming constructs. Here's a one line fibonacci...
PS C:\> 1..10 | foreach{ $i = $j = 1 }{ $k = $i+$j; $i=$j; $j=$k; $k }
2
3
5
8
13
21
34
55
89
144
"1..10" generates a range of numbers from one to ten "|" is a pipe to the next command, "foreach" applies the first statement block once and then the second statement block for each item generated from the previous list.

3 comments:

  1. wicked example!!

    so it does this bit once:
    { $i = $j = 1 }

    then does this bit once for each loop:
    { $k = $i+$j; $i=$j; $j=$k; $k }

    the final $k is printed out (it is the answer...

    is that right??




    ..: secretGeek.net :.

    ReplyDelete
  2. Wow! Secretgeek read my blog! I read secretgeek all the time, that's so cool.

    Yeah, you're spot on, the second code block is executed for each loop. Each statement is seperated by a semicolon and a variable by itself is simply printed to the console.

    ReplyDelete
  3. here's a pinging function i wrote based, that uses my new favourite trick: CursorPosition

    function staticpinger ($address) {
    cls

    #store the cursor position...
    $oldPos = $host.UI.RawUI.CursorPosition


    #do this 100 times...
    1..100 | foreach{

    "Pinging " + $address;

    #let's collect the reply speed for 3 pings.
    $s = ping $address -n 3;


    #and only show the replies...
    $s | foreach{ if($_.IndexOf("Reply") -gt -1){ $_; } };

    #you can sleep between pings if you want
    #Start-Sleep 3;

    #store the final location
    $endPos = $host.UI.RawUI.CursorPosition

    #move back to the top of the console.
    $host.UI.RawUI.CursorPosition = $oldPos ;


    }


    #move the cursor to the end of the area before exiting.
    $host.UI.RawUI.CursorPosition = $endPos;
    }

    #now try:
    staticpinger google.com

    ReplyDelete

Note: only a member of this blog may post a comment.