Semordnilap: Difference between revisions

(→‎{{header|F_Sharp|F#}}: added Forth Section)
Line 812:
 
=={{header|Forth}}==
 
This code uses a Forth wordlist to contain the dictionary, and uses the Forth-2012 TRAVERSE-WORDLIST to walk through it (a simpler way would be to check for the presence of the reversed word when putting the word into the wordlist).
 
One interesting issue is how I get each pair only once and exclude
palindromes: I accept only pairs where nt<nt2. A type checking bigot
will likely argue that nts should not be compared with <, because they
are opaque data types. But their implementation does not matter for
this check: Whatever bit patterns these two nts get, either it's the
same nt, then nt<nt2 will return false, as desired; and if they are
different, exactly one of nt<nt2 and nt2<nt will return true.
 
The code uses two Gforth-specific words: EXECUTE-PARSING (implementable in standard Forth, but not easy) for allowing to provide the name of the defined word on the stack; and FIND-NAME-IN to look up the reversed word (could be replaced with a use of the standard SEARCH-WORDLIST, but the code would become a little more complicated).
 
<lang forth>
wordlist constant dict
under construction
 
: load-dict ( c-addr u -- )
r/o open-file throw >r
begin
pad 1024 r@ read-line throw while
pad swap ['] create execute-parsing
repeat
drop r> close-file throw ;
 
: xreverse {: c-addr u -- c-addr2 u :}
u allocate throw u + c-addr swap over u + >r begin ( from to r:end)
over r@ u< while
over r@ over - x-size dup >r - 2dup r@ cmove
swap r> + swap repeat
r> drop nip u ;
 
: .example ( c-addr u u1 -- )
5 < if
cr 2dup type space 2dup xreverse 2dup type drop free throw then
2drop ;
 
: nt-semicheck ( u1 nt -- u2 f )
dup >r name>string xreverse 2dup dict find-name-in dup if ( u1 c-addr u nt2)
r@ < if ( u1 c-addr u ) \ count pairs only once and not palindromes
2dup 4 pick .example
rot 1+ -rot then
else
drop then
drop free throw r> drop true ;
 
get-current dict set-current s" unixdict.txt" load-dict set-current
 
0 ' nt-semicheck dict traverse-wordlist cr .
cr bye
</lang>
 
Output:
<pre>
suez zeus
paz zap
way yaw
pay yap
may yam
158
</pre>
 
=={{header|Fortran}}==
19

edits