Paste: functional performance

Author: xiackok
Mode: factor
Date: Tue, 15 Feb 2011 04:27:05
Plain Text |
! Copyright (C) 2011 Your name.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors arrays combinators kernel locals math sequences
vectors ;
IN: functional.tailcall

:: reverse ( seq -- seq' )
    seq empty?
    [ seq ]
    [ seq first 1array seq rest reverse prepend ]
    if ;

! tail-call version using locals
:: (reverse-tail) ( seq acc -- seq' )
    seq empty?
    [ acc ]
    [ seq rest acc seq first 1array prepend (reverse-tail) ]
    if ;

! tail-call version without locals
: reverse-tail2 ( seq acc -- seq' )
    over empty?
    [ nip ]
    [ [ dup rest swap first 1array ] dip rot swapd [ prepend ] dip swap reverse-tail2 ]
    if ;

! imperative version - fastest
:: reverse-imperative ( seq -- seq' )
    seq >vector :> seq
    V{ } clone :> seq'
    seq empty?
    [ seq ]
    [
        [ seq empty? not ]
        [
            seq pop seq' push
        ] while seq'
    ] if ;
    

New Annotation

Summary:
Author:
Mode:
Body: