february 2008
  sun mon tue wed thu fri sat  
            1 2  
  3 4 5 6 7 8 9  
  10 11 12 13 14 15 16  
  17 18 19 20 21 22 23  
  24 25 26 27 28 29    

Archives

july 2008 (1)
june 2008 (7)
may 2008 (2)
april 2008 (6)
march 2008 (1)
february 2008 (7)
january 2008 (11)
december 2007 (16)

February 25, 08

Mia unua programo en Forth

[ca] A veure si sabeu què fa el programa.

[eo] Jen. Mi uzis iom da gforth-aj aferoj, jes. Provu diveni, kion la programo faras.

#! /usr/bin/gforth

create stat-array 256 cells allot

4000 constant buffersize
create cbuffer buffersize chars allot

: count-char ( c -- )  \ Updates the stat-array according to the new character read
  cells stat-array + 1 swap +! ;

: read-chars ( -- u2 wior ) \ read chars from the file, and put them into cbuffer
  cbuffer buffersize stdin read-file ;

: clear-stat ( -- ) \ resets the char statistics to 0 for each char
  stat-array 
  256 0 do
    dup 0 swap !
    1 cells +
  loop
  drop ;

: count-chars ( n -- ) \ counts the given amount of chars from the cbuffer
  cbuffer swap 0 do
     dup c@ count-char
    1 chars +
  loop drop ;

: eat-file ( -- ) \ reads chars from a file, and counts them
  begin
    read-chars over swap 0= swap 0> and while
    count-chars
  repeat ;

: show-char ( c -- ) \ shows a character if printable, and outputs its ascii value in []
  dup dup 32 > swap 127 < and if
    dup emit space else 2 spaces then
  [char] [ emit 3 .r [char] ] emit space ;

: show-results ( -- ) \ shows the results of characters counted
  stat-array 
  256 0 do
    dup @ dup 0 if 
    s" Char " type
    i show-char
    s" has occurrences: " type
    . cr
    else drop
    then
    1 cells +
  loop ;

: get-stat ( -- ) \ counts the statistics in stdin, and shows the results.
  clear-stat eat-file show-results ;

get-stat bye
© Published at 22:41 / 0 comments / 199 visits
This post is public

( 1 post )