Odd word problem: Difference between revisions

m
 
(24 intermediate revisions by 15 users not shown)
Line 37:
This is a rather straightforward approach, using recursion.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Odd_Word_Problem is
Line 91:
end if;
end if;
end Odd_Word_Problem;</langsyntaxhighlight>
 
Output:
Line 105:
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
The words and punctuation should be on a single line. Uses recursion.
<langsyntaxhighlight lang="algol68"># recursively reverses the current word in the input and returns the #
# the character that followed it #
# "ch" should contain the first letter of the word on entry and will be #
Line 179:
main: (
reverse every other word
)</langsyntaxhighlight>
{{out}}
<pre>
Line 187:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">str := "what,is,the;meaning,of:life."
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
Line 193:
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res</langsyntaxhighlight>
Outputs:<pre>what,si,the;gninaem,of:efil.</pre>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">OPEN "/dev/stdin" FOR DEVICE AS in
 
FUNCTION get_odd()
Line 238:
CLOSE DEVICE in
 
PRINT</langsyntaxhighlight>
This program uses recursion.
{{out}}
Line 256:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( odd-word
= dothis doother forward backward
. ( forward
Line 288:
& put$\n
& odd-word$"kansas.txt" { Real file, as Bracmat cannot read a single character from stdin. }
);</langsyntaxhighlight>
Output:
<pre>what,si,the;gninaem,of:efil.
Line 294:
 
=={{header|C}}==
Using GCC nested function as closures. This can only be passed up the stack, not the other way around. It's also doable with <code>makecontext</code>, and may be possible with <code>setjmp</code>.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
 
static int
int do_char(int odd, void (*f)(void))
owp(int odd)
{
int ch, ret;
int c = getchar();
ch = getc(stdin);
 
void write_out if (void!odd) {
putc(ch, stdout);
putchar(c);
if (ch == EOF || ch == '.')
if (f) f();
return EOF;
}
if (ispunct(ch))
 
return 0;
if (!odd) putchar(c);
owp(odd);
 
return 0;
if (isalpha(c))
} else {
return do_char(odd, write_out);
if (ispunct(ch))
 
return ch;
if (odd) {
ret = owp(odd);
if (f) f();
putc(ch, stdout);
putchar(c);
return ret;
}
}
 
return c != '.';
}
 
int main()
main(int argc, char **argv)
{
int ich = 1;
while (do_char(ich = owp(!i, 0ch)); != EOF) {
if (ch)
 
putc(ch, stdout);
return 0;
if (ch == '.')
}</lang>
break;
}
return 0;
}
</syntaxhighlight>
 
=={{header|C++}}==
Line 337 ⟶ 342:
Tested with gcc 4.5, with "-std=c++0x" option.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cctype>
#include <functional>
Line 372 ⟶ 377:
while( e ? odd() : even() ) e = !e;
return 0;
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
 
<langsyntaxhighlight lang="ceylon">
String[] meaning = ["what,", "is,", "the;", "meaning,", "of:", "life."];
String[] kansas = ["we,", "are,", "not,", "in,", "kansas;", "any,", "more."];
Line 411 ⟶ 416:
=> ",.:;".contains(char);
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 424 ⟶ 429:
{{trans|Common Lisp}}
 
<langsyntaxhighlight Clojurelang="clojure">(defn next-char []
(char (.read *in*)))
 
Line 449 ⟶ 454:
((backward)))
(recur (not forward?)))) )
(println))</langsyntaxhighlight>
 
Examples:
 
<langsyntaxhighlight lang="clojure">user=> (odd-word "what,is,the;meaning,of:life.")
what,si,the;gninaem,of:efil.
nil
user=> (odd-word "we,are;not,in,kansas;any,more.")
we,era;not,ni,kansas;yna,more.
nil</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight CoffeeScriptlang="coffeescript">isWordChar = (c) -> /^\w/.test c
isLastChar = (c) -> c is '.'
 
Line 497 ⟶ 502:
# Alternate between forward and reverse until one or the other reports that
# the end-of-input mark has been reached (causing a return of false).
continue while forwardWord() and reverseWord()</langsyntaxhighlight>
 
===Same without comments===
 
<langsyntaxhighlight CoffeeScriptlang="coffeescript">isWordChar = (c) -> /^\w/.test c
isLastChar = (c) -> c is '.'
 
Line 523 ⟶ 528:
return not isLastChar(c)
continue while forwardWord() and reverseWord()</langsyntaxhighlight>
 
===Testing code===
 
<langsyntaxhighlight CoffeeScriptlang="coffeescript"># Redefine as necessary for target platform.
println = (z) -> console.log z
 
Line 553 ⟶ 558:
[testString, expectedResult, putBuffer, putBuffer is expectedResult]
 
println result for result in results</langsyntaxhighlight>
 
Output in [[node.js]]:
Line 568 ⟶ 573:
=={{header|Common Lisp}}==
Even words are straightforward. For odd words, the final punctuation is printed by a closure passed back up the caller chain.
<langsyntaxhighlight lang="lisp">(defun odd-word (s)
(let ((stream (make-string-input-stream s)))
(loop for forwardp = t then (not forwardp)
Line 587 ⟶ 592:
(prog1 (backward stream) (write-char ch))
#'(lambda () (write-char ch) (char/= ch #\.)))) )
</syntaxhighlight>
</lang>
 
Examples:
 
<langsyntaxhighlight lang="lisp">? (odd-word "what,is,the;meaning,of:life.")
what,si,the;gninaem,of:efil.
NIL
? (odd-word "we,are;not,in,kansas;any,more.")
we,era;not,ni,kansas;yna,more.
NIL</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">bool doChar(in bool odd, in void delegate() nothrow f=null) nothrow {
import core.stdc.stdio, std.ascii;
 
Line 618 ⟶ 623:
bool i = true;
while (doChar(i = !i)) {}
}</langsyntaxhighlight>
{{out}}
<pre>what,is,the;meaning,of:life.
what,si,the;gninaem,of:efil.</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Console}}
{{libheader| System.Character}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Odd_word_problem;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Console,
System.Character;
 
function doChar(isOdd: boolean; f: TProc = nil): Boolean;
begin
var c: char := Console.ReadKey(True).KeyChar;
 
if not isOdd then
Write(c);
 
if c.IsLetter then
exit(doChar(isOdd,
procedure
begin
Write(c);
if assigned(f) then
f();
end));
 
if isOdd then
begin
if Assigned(f) then
f();
write(c);
end;
 
exit(c <> '.');
 
end;
 
begin
var i: boolean := false;
while doChar(i) do
i := not i;
readln;
end.</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
global inpi inp$ .
func$ read .
inpi += 1
return substr inp$ inpi 1
.
func ispunct c$ .
if c$ = "." or c$ = ":" or c$ = ";" or c$ = ","
return 1
.
return 0
.
func$ handle odd .
c$ = read
if ispunct c$ = 1
return c$
.
if odd = 0
write c$
r$ = handle 0
return r$
else
r$ = handle 1
write c$
return r$
.
.
proc go . .
repeat
c$ = handle odd
write c$
until c$ = "."
odd = 1 - odd
.
print ""
.
repeat
inp$ = input
until inp$ = ""
inpi = 0
go
.
input_data
we,are;not,in,kansas;any,more.
what,is,the;meaning,of:life.
 
</syntaxhighlight>
 
=={{header|EchoLisp}}==
No character input stream in EchoLisp, which runs in a browser window. We simultate it with a character stream, with the only function '''read-char''', as specified in the task.
<langsyntaxhighlight lang="scheme">
(lib 'sequences)
(define input-stream null)
Line 658 ⟶ 760:
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(task "what,is,the;meaning,of:life.")
→ "what,si,the;gninaem,of:efil."
Line 666 ⟶ 768:
(task "Longtemps,je me suis couché,héhé,hôhô,de bonne heure.")
→ "Longtemps,ej me sius couché,éhéh,hôhô,ed bonne erueh."
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Odd_word do
def handle(s, false, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
o.(s)
Line 695 ⟶ 797:
end
 
Odd_word.main</langsyntaxhighlight>
 
{{out}}
Line 705 ⟶ 807:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
handle(S, false, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) ->
O(S),
Line 722 ⟶ 824:
O = fun(S) -> io:put_chars([S]) end,
handle(I(), false, I, O).
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<p>A recursive solution.</p>
<langsyntaxhighlight lang="fsharp">open System
open System.Text.RegularExpressions
 
Line 759 ⟶ 861:
let rec loop () = forward() |> Out; loop()
loop()
0</langsyntaxhighlight>
{{out}}
<pre>
Line 772 ⟶ 874:
This code is difficult to follow, because it twists its control flow like spaghetti. These continuations form a [[singly-linked list]], where each continuation contains a letter and a previous continuation. The program effectively reverses this linked list.
 
<langsyntaxhighlight lang="factor">USING: continuations kernel io io.streams.string locals unicode.categories ;
IN: rosetta.odd-word
 
Line 833 ⟶ 935:
 
: odd-word ( string -- )
[ read-odd-word ] with-string-reader ;</langsyntaxhighlight>
 
'''USE: rosetta.odd-word'''
Line 843 ⟶ 945:
=={{header|FALSE}}==
This solution uses recursion to read the backwards words, to output the characters after having done the rest of that word.
<langsyntaxhighlight lang="false">[$$$$'.=\',=|\';=|\':=|~[^s;!\,]?]s: {recursive reading}
[s;!$'.=~[,^f;!]?]r: {reverse words}
[[$$$$'.=\',=|\';=|\':=|~][,^]#$'.=~[,^r;!]?]f: {forward words}
^f;!, {start}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: word? dup [char] . <> over bl <> and ;
: ?quit dup [char] . = if emit quit then ;
: eatbl begin dup bl = while drop key repeat ?quit ;
: even begin word? while emit key repeat ;
: odd word? if key recurse swap emit then ;
: main cr key eatbl begin even eatbl space odd eatbl space again ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
By not allowing the use of arrays of characters to facilitate the reversing of texts, the obvious solution involves recursion with storage via the stack so that its last-on, first-off style will achieve the required goal. But alas, Fortran compilers were typically written for computers that did not employ a stack mechanism so recursion was not expected even after the introduction of Algol in the 1960s, and the failure of recursively-invoked routines to return correctly became accepted. The standard murmur was that "Fortran is not a recursive language" even though the language contains recursive definitions such as for arithmetic expressions. By contrast, the B6700 system ''did'' employ a hardware stack, and, without any fuss, recursion just worked.
 
But with F90, the language definition was augmented by the menacing word RECURSIVE, and so... <langsyntaxhighlight Fortranlang="fortran"> MODULE ELUDOM !Uses the call stack for auxiliary storage.
INTEGER MSG,INF !I/O unit numbers.
LOGICAL DEFER !To stumble, or not to stumble.
Line 899 ⟶ 1,001:
WRITE (MSG,"('')") !End the line of output.
GO TO 10 !And have another go.
END !That was confusing.</langsyntaxhighlight>
With file Confused.txt containing the obvious input, the output is
<pre>
Line 911 ⟶ 1,013:
 
If the ADVANCE feature is unavailable, then the file could be read as UNFORMATTED, one character at a go with a record length of one. And then would arise the annoyance of dealing with the ASCII world's usage of CR, CRLF, LFCR, or CR as markers for the ends of records.
 
=={{header|FreeBASIC}}==
Rosetta Code problem: https://rosettacode.org/wiki/Odd_word_problem
by Jjuanhdez, 05/2023
<syntaxhighlight lang="vb">Dim Shared As Integer n1 = 1
 
Function reverseString(texto As String) As String
Dim As Integer x, lt = Len(texto)
For x = 0 To lt Shr 1 - 1
Swap texto[x], texto[lt - x - 1]
Next x
Return texto
End Function
 
Sub process(texto As String)
Dim As Integer c = 0, n2
Dim As String tmptexto
Print "Input stream: "; texto
Print "Output stream: ";
Do
n2 = Instr(texto, Any ",;:.")
tmptexto = Mid(texto, n1, n2-1)
Print Iif(c Mod 2 = 0, tmptexto, reverseString(tmptexto)); Mid(texto, n2, 1);
If Mid(texto, n2, 1) = "." Then Exit Do
texto = Mid(texto, n2+1, Len(texto))
c += 1
Loop
Print !"\n"
End Sub
 
process("what,is,the;meaning,of:life.")
process("we,are;not,in,kansas;any,more.")
 
Sleep</syntaxhighlight>
{{out}}
<pre>Input stream: what,is,the;meaning,of:life.
Output stream: what,si,the;gninaem,of:efil.
 
Input stream: we,are;not,in,kansas;any,more.
Output stream: we,era;not,ni,kansas;yna,more.</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
begin globals
short ndx : bool odd : cfstringref stream
end globals
 
local fn recursion
cfstringref ch = mid( stream, ndx, 1 )
if fn StringContainsString( @",;:. ", ch ) == no
ndx++
if odd then fn recursion : print ch; ¬
else print ch; : fn recursion
end if
end fn
 
local fn oddWordTask( s as cfstringref )
ndx = 0 : odd = no : stream = s
print : print, stream : print,
while ndx < len( stream )
fn recursion : print mid( stream, ndx, 1 );
odd = yes - odd : ndx++
wend
print
end fn
 
window 1, @"Odd word task in FutureBasic", (0,0,310,155)
fn oddWordTask( @"what,is,the;meaning,of:life." )
fn oddWordTask( @"we,are;not,in,kansas;any,more." )
fn oddWordTask( @"This also works with normal spaces." )
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:FB output for Odd Word Task.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 964 ⟶ 1,144:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 972 ⟶ 1,152:
 
===Using <code>defer</code>===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,023 ⟶ 1,203:
}
}
}</langsyntaxhighlight>
 
===Using channels and goroutines===
{{trans|Ruby}}
{{trans|Tcl}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,116 ⟶ 1,296:
close(f.in)
close(r.in)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
While it seems like this solution would break the task's rules, Haskell is non-strict, therefore this yields the same behavior of reading and printing one character at a time, without excess storage into a "string". To prove it, run the program and manually enter the input string (Windows command prompt does not respect buffering settings, but urxvt on on Linux does).
<langsyntaxhighlight Haskelllang="haskell">import System.IO
(BufferMode(..), getContents, hSetBuffering, stdin, stdout)
import Data.Char (isAlpha)
Line 1,140 ⟶ 1,320:
hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> getContents >>=
putStr . takeWhile (/= '.') . parse >>
putStrLn "."</langsyntaxhighlight>
If the above is not acceptable, or if Haskell was implicitly strict, then this solution would satisfy the requirements:
<langsyntaxhighlight Haskelllang="haskell">isAlpha :: Char -> Bool
isAlpha = flip elem $ ['a'..'z'] ++ ['A'..'Z']
 
Line 1,172 ⟶ 1,352:
main :: IO ()
main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >>
parse >> putStrLn ""</langsyntaxhighlight>
Linux urxvt output:
<pre>$ ./OddWord
Line 1,194 ⟶ 1,374:
The following recursive version is based on the non-deferred GO version. A co-expression is used to turn the parameter to the wrapper into a character at a time stream.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
every OddWord(!["what,is,the;meaning,of:life.",
"we,are;not,in,kansas;any,more."])
Line 1,215 ⟶ 1,395:
if any(marks,s := @stream) then return s
return 1(oWord(stream,marks), writes(s))
end</langsyntaxhighlight>
 
Output:<pre>Input stream: what,is,the;meaning,of:life.
Line 1,223 ⟶ 1,403:
 
A slightly different solution which uses real I/O from stdin is:
<langsyntaxhighlight Uniconlang="unicon">procedure main(A)
repeat (while writes((any(&letters, c := reads(&input,1)),c))) |
(writes(c) ~== "." ~== writes(rWord())) | break write()
Line 1,232 ⟶ 1,412:
writes(\c)
return c1
end</langsyntaxhighlight>
And some sample runs:
<pre>
Line 1,249 ⟶ 1,429:
J also lacks character stream support, so this implementation uses a [[Odd_word_problem/TrivialCharacterStreamSupportForJ|stream-like implementation]].
 
<langsyntaxhighlight lang="j">putch=: 4 :0 NB. coroutine verb
outch y
return x
Line 1,274 ⟶ 1,454:
outch char=. do_char coroutine ''
end.
)</langsyntaxhighlight>
 
Note that in the couroutine-like support page we defined <code>u yield v y</code> such that it produces a result which, when returned to the <code>coroutine</code> helper verb, will cause the deferred execute <code>u v y</code> in a context where both u and v are expected to be coroutine verbs (they will produce a result either wrapped with <code>yield</code> or with <code>return</code>). Likewise <code>return</code> wraps the result with instructions for the <code>coroutine</code> helper, instructing it to use the returned result "as-is". (And, if <code>return</code> is used with an empty stack in the helper, that instance would be the result of the <code>coroutine</code> helper.)
Line 1,282 ⟶ 1,462:
With this implementation:
 
<langsyntaxhighlight lang="j"> evenodd 'what,is,the;meaning,of:life.'
what,si,the;gninaem,of:efil.
evenodd 'we,are;not,in,kansas;any,more.'
we,era;not,ni,kansas;yna,more.</langsyntaxhighlight>
 
That said, note that this implementation has significant overhead when compared to a more direct implementation of the algorithm.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class OddWord {
interface CharHandler {
CharHandler handle(char c) throws Exception;
Line 1,346 ⟶ 1,526:
new OddWord().loop();
}
}</langsyntaxhighlight>
Output is equivalent to that of the Python solution.
 
Line 1,352 ⟶ 1,532:
{{works with|Julia|0.6}}
{{trans|Python}}
<langsyntaxhighlight lang="julia"># io = readstring(STDIN)
io = "what,is,the;meaning,of:life."
i = 0
Line 1,384 ⟶ 1,564:
while evn ? odd() : even()
evn = !evn
end</langsyntaxhighlight>
 
{{out}}
Line 1,391 ⟶ 1,571:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Func = () -> Unit
Line 1,421 ⟶ 1,601:
println("\n")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,434 ⟶ 1,614:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define odd_word_processor(str::string) => {
local(
isodd = false,
Line 1,487 ⟶ 1,667:
'new:\r'
odd_word_processor('what,is,the;meaning,of:life.')
'\rShould have:\rwhat,si,the;gninaem,of:efil.'</langsyntaxhighlight>
 
{{out}}
Line 1,498 ⟶ 1,678:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function reverse()
local ch = io.read(1)
if ch:find("%w") then
Line 1,520 ⟶ 1,700:
end
 
while forward() do end</langsyntaxhighlight>
{{out}}
<pre>$ echo what,is,the;meaning,of:life.|oddword.lua
Line 1,537 ⟶ 1,717:
We can pass by reference the lambda function but here we pass by reference the f factor, which for keyboard check the end, and for file work as file handler and at then end as a flag which check the end.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
global out$
Line 1,625 ⟶ 1,805:
}
Checkit
</syntaxhighlight>
</lang>
===Using Closure===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module OddWord {
k$=lambda$->""
Line 1,650 ⟶ 1,830:
Keyboard "we,are;not,in,kansas;any,more."
OddWord
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,659 ⟶ 1,839:
 
=={{header|Nim}}==
===Using a closure===
{{trans|Python}}
<syntaxhighlight lang ="nim">import os, unicode, future
 
proctype nothingProc = proc(): bool {.closure.} = false
 
var nothing: Proc = proc(): bool {.closure.} = false
 
proc odd(prev = nothing): bool =
Line 1,687 ⟶ 1,870:
var e = false
while (if e: odd() else: even()):
e = not e</langsyntaxhighlight>
 
Output:
{{out}}
<pre>$ echo "what,is,the;meaning,of:life." | ./oddword
what,si,the;gninaem,of:efil.
echo "we,are;not,in,kansas;any,more." | ./oddword
we,era;not,ni,kansas;yna,more.</pre>
 
===Using recursion===
{{trans|ALGOL 68}}
<syntaxhighlight lang="nim">import strutils
 
proc reverseWord(ch: var char) =
var nextch = stdin.readChar()
if nextch.isAlphaAscii():
reverseWord(nextch)
stdout.write(ch)
ch = nextch
 
proc normalWord(ch: var char) =
stdout.write(ch)
ch = stdin.readChar()
if ch.isAlphaAscii():
normalWord(ch)
 
var ch = stdin.readChar()
 
while ch != '.':
normalWord(ch)
if ch != '.':
stdout.write(ch)
ch = stdin.readChar()
reverseWord(ch)
stdout.write(ch)</syntaxhighlight>
 
{{out}}
Same as with the closure version.
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let is_alpha c =
c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z'
Line 1,720 ⟶ 1,934:
let () =
try rev_odd_words ()
with End_of_file -> ()</langsyntaxhighlight>
 
Executing:
Line 1,729 ⟶ 1,943:
=={{header|Ol}}==
Use string iterators.
<langsyntaxhighlight lang="scheme">
(define (odd_word_problem words)
(letrec ((odd (lambda (s out)
Line 1,761 ⟶ 1,975:
(odd_word_problem "what,is,the;meaning,of:life.")
(odd_word_problem "we,are;not,in,kansas;any,more.")
</syntaxhighlight>
</lang>
 
Output:
Line 1,778 ⟶ 1,992:
 
===Closure version===
<langsyntaxhighlight Perllang="perl">sub r
{
my ($f, $c) = @_;
Line 1,797 ⟶ 2,011:
}
}
$r->();</langsyntaxhighlight>
===Recursion version===
<langsyntaxhighlight Perllang="perl">sub rev
{
my $c;
Line 1,824 ⟶ 2,038:
$n = 0; $l = 0;
}
}</langsyntaxhighlight>
===Threads (processes) version===
Perl still has weak threads support. Far more safe yet portable is to use processes (fork).
 
Here, fork is used instead of threads and pipe is used instead of conditional variable.
<langsyntaxhighlight Perllang="perl">$|=1;
 
while (read STDIN, $_, 1) {
Line 1,852 ⟶ 2,066:
close R;
}
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,858 ⟶ 2,072:
To test direct console input, comment out string s .. getchar(), and uncomment getc(0) and the prompt.<br>
Likewise use integer fn = open("somefile","r"), and getc(fn) should you want to test file i/o.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>string s = "what,is,the;meaning,of:life."
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
--string s = "we,are;not,in,kansas;any,more."
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"what,is,the;meaning,of:life."</span>
integer i = 0
<span style="color: #000080;font-style:italic;">--string s = "we,are;not,in,kansas;any,more."</span>
 
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
function getchar()
i += 1
<span style="color: #008080;">function</span> <span style="color: #000000;">getchar</span><span style="color: #0000FF;">()</span>
return s[i]
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function wrod(integer rev)
integer ch = getchar(), nch
<span style="color: #008080;">function</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
-- integer ch = getc(0), nch
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">getchar</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">nch</span>
if not find(ch," .,:;!?") then
<span style="color: #000080;font-style:italic;">-- integer ch = getc(0), nch</span>
if rev then
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" .,:;!?"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
nch = wrod(rev)
<span style="color: #008080;">if</span> <span style="color: #000000;">rev</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">nch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
puts(1,ch)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if not rev then
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
nch = wrod(rev)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">rev</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">nch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
ch = nch
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nch</span>
return ch
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">ch</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
--puts(1,"Enter words separated by a single punctuation mark (i.e. !?,.;:) and ending with .\n")
integer rev = 0
<span style="color: #000080;font-style:italic;">--puts(1,"Enter words separated by a single punctuation mark (i.e. !?,.;:) and ending with .\n")</span>
while 1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">rev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
integer ch = wrod(rev)
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
puts(1,ch)
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
if ch='.' then exit end if
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
rev = 1-rev
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'.'</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while</lang>
<span style="color: #000000;">rev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">rev</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,899 ⟶ 2,116:
=={{header|PHP}}==
{{trans|Python}}
<langsyntaxhighlight PHPlang="php">$odd = function ($prev) use ( &$odd ) {
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
Line 1,925 ⟶ 2,142:
while ($e ? $odd($prev) : $even()) {
$e = !$e;
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de oddWords ()
(use C
(loop
Line 1,941 ⟶ 2,158:
C
(prog1 (recurse (char)) (prin C)) ) ) ) ) ) )
(prinl) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(in "txt1" (oddWords))
(in "txt2" (oddWords))</langsyntaxhighlight>
Output:
<pre>what,si,the;gninaem,of:efil.
Line 1,951 ⟶ 2,168:
=={{header|PL/I}}==
 
<langsyntaxhighlight PLlang="pl/Ii">test: procedure options (main); /* 2 August 2014 */
declare (ch, ech) character (1);
declare odd file;
Line 1,975 ⟶ 2,192:
if ech = '.' then leave;
end;
end test;</langsyntaxhighlight>
file:
<pre>
Line 1,995 ⟶ 2,212:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">odd_word_problem :-
read_line_to_codes(user_input, L),
even_word(L, Out, []),
Line 2,022 ⟶ 2,239:
[H],
even_word(T).
</syntaxhighlight>
</lang>
Output :
<pre>?- odd_word_problem.
Line 2,037 ⟶ 2,254:
=={{header|PureBasic}}==
This example uses recursion.
<langsyntaxhighlight PureBasiclang="purebasic">#False = 0
#True = 1
 
Line 2,094 ⟶ 2,311:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Enter a series of words consisting only of English letters (i.e. a-z, A-Z)
Line 2,107 ⟶ 2,324:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from sys import stdin, stdout
 
def char_in(): return stdin.read(1)
Line 2,134 ⟶ 2,351:
e = False
while odd() if e else even():
e = not e</langsyntaxhighlight>
Running:<syntaxhighlight lang="text">$ echo "what,is,the;meaning,of:life." | python odd.py
what,si,the;gninaem,of:efil.
$ echo "we,are;not,in,kansas;any,more." | python odd.py
we,era;not,ni,kansas;yna,more.</langsyntaxhighlight>
 
{{trans|Scheme}}
In this version, the action of printing the terminating punctuation is put in a closure and returned by <code>odd()</code>.
<langsyntaxhighlight lang="python">from sys import stdin, stdout
 
def char_in(): return stdin.read(1)
Line 2,169 ⟶ 2,386:
e = False
while odd()() if e else even():
e = not e</langsyntaxhighlight>
 
===Using coroutines and recursion===
Line 2,175 ⟶ 2,392:
{{trans|Tcl}}
{{works with|Python|3.3+}}
<langsyntaxhighlight lang="python">from sys import stdin, stdout
 
def fwd(c):
Line 2,207 ⟶ 2,424:
if not c:
break
coro = coro.send(c)</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
It is not possible to comply with the requirements of this task ''to the letter'' as the task presumes the existence of an ''implicit'' stack, e.g. a stack frame storing state information during subroutine calls, including recursive calls. In Quackery such information is stored on a second stack (usually referred to as ''the stack'') which is ''explicit''.
 
Also, there is no character-at-a-time input stream mechanism implemented in Quackery. Instead, the code uses the word <code>behead</code> which equivalently returns successive characters from a string, one at a time.
 
Therefore this solution is in the spirit of the requirements, if not the letter.
 
<syntaxhighlight lang="quackery">[ upper dup lower != ] is letter ( c --> b )
 
forward is backwords ( $ --> $ )
 
[ [ behead
dup letter while
emit again ]
dup emit
char . !=
if backwords ] is forwords ( $ --> $ )
 
[ [ behead
dup letter while
swap recurse
rot emit ]
dup emit
char . !=
if forwords ] resolves backwords ( $ --> $ )
 
[ forwords drop cr ] is oddwords ( $ --> )
 
$ "we,are;not,in,kansas;any,more." oddwords
$ "what,is,the;meaning,of:life." oddwords</syntaxhighlight>
 
{{out}}
 
<pre>we,era;not,ni,kansas;yna,more.
what,si,the;gninaem,of:efil.</pre>
 
=={{header|Racket}}==
Simple solution, using a continuation thunk for the reverse parts.
<langsyntaxhighlight lang="racket">
#!/bin/sh
#|
Line 2,238 ⟶ 2,492:
;; (with-input-from-string "we,are;not,in,kansas;any,more." main)
;; ;; -> we,era;not,ni,kansas;yna,more.
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
A recursive solution, with the added feature that it treats each line separately.
<syntaxhighlight lang="raku" perl6line>my &in = { $*IN.getc // last }
 
loop {
Line 2,254 ⟶ 2,508:
 
multi ow ($_ where /\w/) { ow(in) x .print; }
multi ow ($_) { $_; }</langsyntaxhighlight>
{{out}}
<pre>$ ./oddword
Line 2,273 ⟶ 2,527:
 
No recursion or the stack is used. &nbsp; The program could've been written without subroutines.
<langsyntaxhighlight lang="rexx">/*REXX program solves the odd word problem by only using (single) byte input/output.*/
iFID_ = 'ODDWORD.IN' /*Note: numeric suffix is added later.*/
oFID_ = 'ODDWORD.' /* " " " " " " */
Line 2,303 ⟶ 2,557:
/*──────────────────────────────────────────────────────────────────────────────────────*/
rChar: if arg()==0 then do; x= charin(iFID); #= #+1; end /*read next char*/
else x= charin(iFID, arg(1) ); /* " specific " */ return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the two (default) input files which contain:}}
:* &nbsp; input file &nbsp; '''ODDWORD.IN1''' &nbsp; ───► &nbsp; <tt> what,is,the;meaning,of:life. </tt>
Line 2,320 ⟶ 2,574:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Odd word problem
 
Line 2,364 ⟶ 2,618:
next
return cStr2
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,376 ⟶ 2,630:
{{trans|Tcl}}
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby">f, r = nil
fwd = proc {|c|
c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c }
Line 2,388 ⟶ 2,642:
until $stdin.eof?
coro = coro.resume($stdin.getc)
end</langsyntaxhighlight>
 
===Using continuations===
{{trans|Factor}}
{{libheader|continuation}}
<langsyntaxhighlight lang="ruby">require 'continuation' unless defined? Continuation
require 'stringio'
 
Line 2,463 ⟶ 2,717:
 
odd_word "what,is,the;meaning,of:life."
odd_word "we,are;not,in,kansas;any,more."</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
{{incorrect|Run BASIC|Restriction #1 violated - only single character I/O allowed. Restriction #2 violated - explicit storage in string for later reversal not allowed.}}
<langsyntaxhighlight lang="runbasic">open "oddWord.txt" for input as #f ' read input stream
while not(eof(#f))
line input #f, a$
Line 2,497 ⟶ 2,751:
next ii
wend
close #f</langsyntaxhighlight>
<pre>what,is,the;meaning,of:life. -> what,si,the;gninaem,of:efil.
we,are;not,in,kansas;any,more. -> we,era;not,ni,kansas;yna,more.</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import scala.io.Source
import java.io.PrintStream
 
Line 2,518 ⟶ 2,772:
 
process(Source.fromString("what,is,the;meaning,of:life."), System.out); println
process(Source.fromString("we,are;not,in,kansas;any,more."), System.out); println</langsyntaxhighlight>
{{out}}
<pre>what,si,the;gninaem,of:efil.
Line 2,525 ⟶ 2,779:
=={{header|Scheme}}==
Output is identical to python.
<langsyntaxhighlight lang="lisp">(define (odd)
(let ((c (read-char)))
(if (char-alphabetic? c)
Line 2,543 ⟶ 2,797:
(if (if i ((odd)) (even))
(exit)
(loop (not i))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "chartype.s7i";
 
Line 2,580 ⟶ 2,834:
until delimiter = '.';
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,593 ⟶ 2,847:
Recursive solution:
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func rev {
(var c = STDIN.getc) \\ return()
if (c ~~ /^[a-z]\z/i) {
Line 2,616 ⟶ 2,870:
l = false
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,629 ⟶ 2,883:
Although the input is handled as strings, they're all as single-character strings.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc fwd c {
Line 2,641 ⟶ 2,895:
for {set coro f} {![eof stdin]} {} {
set coro [$coro [read stdin 1]]
}</langsyntaxhighlight>
Output is identical to Python and Scheme versions.
 
Line 2,649 ⟶ 2,903:
{{incorrect|Run BASIC|You are supposed to read characters one by one and not store them in arrays.}}
 
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
inputstring=*
Line 2,668 ⟶ 2,922:
PRINT outputstring
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,677 ⟶ 2,931:
=={{header|VBA}}==
First way :
<langsyntaxhighlight lang="vb">Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Line 2,711 ⟶ 2,965:
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function</langsyntaxhighlight>
Second way :
<langsyntaxhighlight lang="vb">Private Function OddWordSecond(Words As String) As String
Dim i&, count&, t$, cpt&, j&, l&, d&, f As Boolean
Const PUNCT As String = ",;:"
Line 2,751 ⟶ 3,005:
Next
OddWordSecond = t
End Function</langsyntaxhighlight>
To call Functions :
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 2,763 ⟶ 3,017:
Debug.Print "First way : " & OddWordFirst("what,is,the;meaning,of:life.")
Debug.Print "Second way : " & OddWordSecond("what,is,the;meaning,of:life.")
End Sub</langsyntaxhighlight>
{{out}}
<pre>Input : we,are;not,in,kansas;any,more.
Line 2,772 ⟶ 3,026:
First way : what,si,the;gninaem,of:efil.
Second way : what,si,the;gninaem,of:efil.</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const str = 'what,is,the;meaning,of:life.'
 
fn main() {
mut temp, mut new_str := '', ''
mut switch := true
for field in str {
temp += field.ascii_str()
if field.is_alnum() == false {
if switch == true {
new_str += temp
temp =''
switch = false
continue
}
else {
new_str += temp.all_before_last(field.ascii_str()).reverse() + field.ascii_str()
temp =''
switch = true
continue
}
}
}
println(new_str)
}
</syntaxhighlight>
 
{{out}}
<pre>
what,si,the;gninaem,of:efil.
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin,Stdout
import "./str" for Char
 
var fwrite = Fn.new { |ch|
Line 2,809 ⟶ 3,096:
Stdin.readByte() // remove \n from buffer
System.print("\n")
}</langsyntaxhighlight>
 
{{out}}
Line 2,819 ⟶ 3,106:
we,era;not,ni,kansas;yna,more.
 
</pre>
 
=={{header|XPL0}}==
{{trans|Go}}
<syntaxhighlight lang "XPL0">proc OWP;
int B;
func Odd;
int S, B;
[S:= ChIn(8);
if S < ^A then \punct\ return S;
B:= Odd;
ChOut(0, S);
return B;
];
 
[OpenI(8);
loop [loop [B:= ChIn(8);
ChOut(0, B);
if B = ^. then return;
if B < ^A \punct\ then quit;
];
B:= Odd;
ChOut(0, B);
if B = ^. then return;
];
];
 
[OpenO(8);
Text(8, "what,is,the;meaning,of:life. ");
OWP;
CrLf(0);
 
OpenO(8);
Text(8, "we,are;not,in,kansas;any,more. ");
OWP;
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
what,si,the;gninaem,of:efil.
we,era;not,ni,kansas;yna,more.
</pre>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">var [const] delim=",:;/?!@#$%^&*()_+", stop=".";
fcn oddly(inStream){
inStream=inStream.walker(3); // character iterator: string, file, etc
Line 2,837 ⟶ 3,165:
while(doWord(inStream, tf.next(), Void)) {}
println();
}</langsyntaxhighlight>
Showing two different input streams:
<langsyntaxhighlight lang="zkl">oddly("what,is,the;meaning,of:life.");
oddly(Data(0,String,"we,are;not,in,kansas;any,more."));</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits