Odd word problem: Difference between revisions

m
 
(42 intermediate revisions by 19 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 101:
we,are;not,in,kansas;any,more.
we,era;not,ni,kansas;yna,more.</pre>
 
=={{header|ALGOL 68}}==
{{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 178 ⟶ 179:
main: (
reverse every other word
)</langsyntaxhighlight>
{{out}}
<pre>
Line 186 ⟶ 187:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">str := "what,is,the;meaning,of:life."
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
Line 192 ⟶ 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 237 ⟶ 238:
CLOSE DEVICE in
 
PRINT</langsyntaxhighlight>
This program uses recursion.
{{out}}
Line 255 ⟶ 256:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( odd-word
= dothis doother forward backward
. ( forward
Line 287 ⟶ 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 293 ⟶ 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 336 ⟶ 342:
Tested with gcc 4.5, with "-std=c++0x" option.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cctype>
#include <functional>
Line 371 ⟶ 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 410 ⟶ 416:
=> ",.:;".contains(char);
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 423 ⟶ 429:
{{trans|Common Lisp}}
 
<langsyntaxhighlight Clojurelang="clojure">(defn next-char []
(char (.read *in*)))
 
Line 448 ⟶ 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 496 ⟶ 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 522 ⟶ 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 552 ⟶ 558:
[testString, expectedResult, putBuffer, putBuffer is expectedResult]
 
println result for result in results</langsyntaxhighlight>
 
Output in [[node.js]]:
Line 567 ⟶ 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 586 ⟶ 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 617 ⟶ 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 657 ⟶ 760:
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(task "what,is,the;meaning,of:life.")
→ "what,si,the;gninaem,of:efil."
Line 665 ⟶ 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 694 ⟶ 797:
end
 
Odd_word.main</langsyntaxhighlight>
 
{{out}}
Line 704 ⟶ 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 721 ⟶ 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 758 ⟶ 861:
let rec loop () = forward() |> Out; loop()
loop()
0</langsyntaxhighlight>
{{out}}
<pre>
Line 771 ⟶ 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 832 ⟶ 935:
 
: odd-word ( string -- )
[ read-odd-word ] with-string-reader ;</langsyntaxhighlight>
 
'''USE: rosetta.odd-word'''
Line 842 ⟶ 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 898 ⟶ 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 910 ⟶ 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 963 ⟶ 1,144:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 971 ⟶ 1,152:
 
===Using <code>defer</code>===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,022 ⟶ 1,203:
}
}
}</langsyntaxhighlight>
 
===Using channels and goroutines===
{{trans|Ruby}}
{{trans|Tcl}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,115 ⟶ 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)
isAlpha :: Char -> Bool
isAlpha = flip elem $ ['a'..'z'] ++ ['A'..'Z']
 
split :: String -> (String, String)
split = break $ not .span isAlpha
 
parse :: String -> String
parse [] = []
parse l =
let (a, w) = split l
(b, x) = splitAt 1 w
(c, y) = split x
(d, z) = splitAt 1 y
in a ++<> b ++<> reverse c ++<> d ++<> parse z
 
main :: IO ()
main =
main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >>
hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> getContents >>=
getContents >>= putStr . (takeWhile (/= '.')) . parse >> putStrLn "."</lang>
putStr . takeWhile (/= '.') . parse >>
putStrLn "."</syntaxhighlight>
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,170 ⟶ 1,352:
main :: IO ()
main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >>
parse >> putStrLn ""</langsyntaxhighlight>
Linux urxvt output:
<pre>$ ./OddWord
Line 1,192 ⟶ 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,213 ⟶ 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,221 ⟶ 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,230 ⟶ 1,412:
writes(\c)
return c1
end</langsyntaxhighlight>
And some sample runs:
<pre>
Line 1,247 ⟶ 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,272 ⟶ 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,280 ⟶ 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,344 ⟶ 1,526:
new OddWord().loop();
}
}</langsyntaxhighlight>
Output is equivalent to that of the Python solution.
 
Line 1,350 ⟶ 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,382 ⟶ 1,564:
while evn ? odd() : even()
evn = !evn
end</langsyntaxhighlight>
 
{{out}}
Line 1,389 ⟶ 1,571:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Func = () -> Unit
Line 1,419 ⟶ 1,601:
println("\n")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,432 ⟶ 1,614:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define odd_word_processor(str::string) => {
local(
isodd = false,
Line 1,485 ⟶ 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,494 ⟶ 1,676:
Should have:
what,si,the;gninaem,of:efil.</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function reverse()
local ch = io.read(1)
if ch:find("%w") then
local rc = reverse()
io.write(ch)
return rc
end
return ch
end
 
function forward()
ch = io.read(1)
io.write(ch)
if ch == "." then return false end
if not ch:find("%w") then
ch = reverse()
if ch then io.write(ch) end
if ch == "." then return false end
end
return true
end
 
while forward() do end</syntaxhighlight>
{{out}}
<pre>$ echo what,is,the;meaning,of:life.|oddword.lua
what,si,the;gninaem,of:efil.
 
$ echo we,are;not,in,kansas;any,more.|oddword.lua
we,era;not,ni,kansas;yna,more.</pre>
 
=={{header|M2000 Interpreter}}==
 
<lang M2000 Interpreter>
===Using Recursion===
PepareStream$() with null string set a lambda which read from keyboard and end reading when . found.
 
PepareStream$() with not a null string make a file and set a lambda to read it
So code works with any stream, until get a null string
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">
Module Checkit {
global out$
Line 1,502 ⟶ 1,723:
Function PrepareStream$ (buf$) {
\\ get a temporary file
if buf$="" then {
class ref {
f
class:
module ref (.f) { }
}
\\ make f closure by reference
m->ref(false)
=lambda$ m->{
if m=>f then exit
r$=Key$
m=>f=r$="."
=r$
}
\\ exit function
break
}
name$=tempname$
\\ we use Ansi type files
Line 1,509 ⟶ 1,747:
Open name$ for input as #f
class ref {
f
class:
module ref (.f) { }
Line 1,523 ⟶ 1,761:
}
}
Module Odd(c$) {
one$=""
Line 1,533 ⟶ 1,770:
Print one$;
out$<=one$
Call MyOddMyEven, c$, &last$
}
Module MyOdd(c$, &last$) {
Line 1,542 ⟶ 1,779:
\\ print after
Print one$;
out$<=one$
}
Do {
Line 1,555 ⟶ 1,792:
Print one$;
out$<=one$
} Always
Print
out$<={
}
}
\\ Feeding keyboard
Odd PrepareStream$("what,is,the;meaning,of:life.")
keyboard "what,is,the;meaning,of:life."
Odd PrepareStream$("")
\\ Use a file for input
Odd PrepareStream$("we,are;not,in,kansas;any,more.")
clipboard out$
}
Checkit
</syntaxhighlight>
</lang>
===Using Closure===
<syntaxhighlight lang="m2000 interpreter">
Module OddWord {
k$=lambda$->""
state=false
odd=True
do {
a$=key$
if a$ ~"[a-zA-Z]" then {
If state Else state~ : odd~
if state and odd then k$=lambda$ k$, a$->a$+k$() : Continue
Print a$;
} Else {
If state Then state~
if odd then Print k$(); : k$=lambda$->""
Print a$;
}
} until a$="."
Print
}
keyboard "what,is,the;meaning,of:life."
OddWord
Keyboard "we,are;not,in,kansas;any,more."
OddWord
</syntaxhighlight>
 
{{out}}
<pre>
Line 1,573 ⟶ 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,601 ⟶ 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,634 ⟶ 1,934:
let () =
try rev_odd_words ()
with End_of_file -> ()</langsyntaxhighlight>
 
Executing:
Line 1,643 ⟶ 1,943:
=={{header|Ol}}==
Use string iterators.
<langsyntaxhighlight lang="scheme">
(define (odd_word_problem words)
(letrec ((odd (lambda (s out)
Line 1,675 ⟶ 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,682 ⟶ 1,982:
we,era;not,ni,kansas;yna,more.
</pre>
 
 
=={{header|Perl}}==
Line 1,693 ⟶ 1,992:
 
===Closure version===
<langsyntaxhighlight Perllang="perl">sub r
{
my ($f, $c) = @_;
Line 1,712 ⟶ 2,011:
}
}
$r->();</langsyntaxhighlight>
===Recursion version===
<langsyntaxhighlight Perllang="perl">sub rev
{
my $c;
Line 1,739 ⟶ 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,767 ⟶ 2,066:
close R;
}
}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
A recursive solution, with the added feature that it treats each line separately.
<lang perl6>my &in = { $*IN.getc // last }
 
loop {
ew(in);
ow(in).print;
}
 
multi ew ($_ where /\w/) { .print; ew(in); }
multi ew ($_) { .print; next when "\n"; }
 
multi ow ($_ where /\w/) { ow(in) x .print; }
multi ow ($_) { $_; }</lang>
{{out}}
<pre>$ ./oddword
we,are;not,in,kansas;any,more.
we,era;not,ni,kansas;yna,more.
what,is,the;meaning,of:life.
what,si,the;gninaem,of:efil.</pre>
Note how the even/oddness is reset on the line boundary; if not, the second line might have started out in an odd state and reversed "what" instead of "is". The call to <tt>next</tt> prevents that by sending the loop back to its initial state.
 
There is one clever trick here with the <tt>x</tt> operator; it evaluates both its arguments in order, but in this case only returns the left argument because the right one is always 1 (True). You can think of it as a reversed C-style comma operator.
 
=={{header|Phix}}==
Line 1,797 ⟶ 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,838 ⟶ 2,116:
=={{header|PHP}}==
{{trans|Python}}
<langsyntaxhighlight PHPlang="php">$odd = function ($prev) use ( &$odd ) {
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
Line 1,864 ⟶ 2,142:
while ($e ? $odd($prev) : $even()) {
$e = !$e;
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de oddWords ()
(use C
(loop
Line 1,880 ⟶ 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,889 ⟶ 2,167:
 
=={{header|PL/I}}==
 
<lang PL/I>test: procedure options (main); /* 2 August 2014 */
<syntaxhighlight lang="pl/i">test: procedure options (main); /* 2 August 2014 */
declare (ch, ech) character (1);
declare odd file;
Line 1,913 ⟶ 2,192:
if ech = '.' then leave;
end;
end test;</langsyntaxhighlight>
file:
<pre>
Line 1,933 ⟶ 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 1,960 ⟶ 2,239:
[H],
even_word(T).
</syntaxhighlight>
</lang>
Output :
<pre>?- odd_word_problem.
Line 1,972 ⟶ 2,251:
true .
</pre>
 
=={{header|PureBasic}}==
This example uses recursion.
<langsyntaxhighlight PureBasiclang="purebasic">#False = 0
#True = 1
 
Line 2,031 ⟶ 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,044 ⟶ 2,324:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from sys import stdin, stdout
 
def char_in(): return stdin.read(1)
Line 2,071 ⟶ 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,106 ⟶ 2,386:
e = False
while odd()() if e else even():
e = not e</langsyntaxhighlight>
 
===Using coroutines and recursion===
Line 2,112 ⟶ 2,392:
{{trans|Tcl}}
{{works with|Python|3.3+}}
<langsyntaxhighlight lang="python">from sys import stdin, stdout
 
def fwd(c):
Line 2,144 ⟶ 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,175 ⟶ 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" line>my &in = { $*IN.getc // last }
 
loop {
ew(in);
ow(in).print;
}
 
multi ew ($_ where /\w/) { .print; ew(in); }
multi ew ($_) { .print; next when "\n"; }
 
multi ow ($_ where /\w/) { ow(in) x .print; }
multi ow ($_) { $_; }</syntaxhighlight>
{{out}}
<pre>$ ./oddword
we,are;not,in,kansas;any,more.
we,era;not,ni,kansas;yna,more.
what,is,the;meaning,of:life.
what,si,the;gninaem,of:efil.</pre>
Note how the even/oddness is reset on the line boundary; if not, the second line might have started out in an odd state and reversed "what" instead of "is". The call to <tt>next</tt> prevents that by sending the loop back to its initial state.
 
There is one clever trick here with the <tt>x</tt> operator; it evaluates both its arguments in order, but in this case only returns the left argument because the right one is always 1 (True). You can think of it as a reversed C-style comma operator.
 
=={{header|REXX}}==
The REXX program writes some header information to aid in visual fidelity when displaying the output to the
<br>screen (also a blank line is written to make the screen display righteous; &nbsp; it's assumed that writing titles and
<br>blank lines doesn't break the spirit of the restrictions (single character I/O) &nbsp; [the 8<sup>th</sup> line with the three <big><big>'''say'''</big></big>s].
three &nbsp; <big>'''say'''</big><small>s</small>].
<br>This displaying of informative messages is only to help the observer to know what is being performed.
 
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' iFID_ = 'ODDWORD.IN' /*Note: numeric suffix is added later.*/
oFID_ = 'ODDWORD.' oFID_ = 'ODDWORD.' /* " " " " " " */
do case=1 for 2; #= 0 /*#: is the number of characters read.*/
 
do caseiFID=1 iFID_ for 2;|| case #=0 /*#:read is theODDWORD.IN1 number ofor characters readODDWORD.IN2 */
iFIDoFID=iFID_ oFID_ || case /*read write ODDWORD.IN11 or ODDWORD.IN22 */
oFID=oFID_ || case /*write ODDWORD.1 o r ODDWORD.2 */
say; say; say '════════ reading file: ' iFID "════════" /* ◄■■■■■■■■■ optional. */
 
do until x==. /* [↓] perform for until "odd"reaching a words.period*/
do until \isMixdatatype(x, 'M'); /* [↓] " " /* [↓] perform until punctpunctuation found.*/
call readChar;rChar call writeChar /*read and write a lettersingle character. */
end /*until ¬isMix(x)*/call wChar /*write [↑]" " keep reading " " */
if x==. then leave end /*until \data···*/ /*is this[↑] the read/write end─of─sentenceuntil ?punctuation. */
callif readLetters;x==. then leave punct=# /*saveis thethis locationthe ofend─of─sentence punctuation(period)?*/
call readLetters; do j=#-1 by -1; call readChar j punct= # /*save the location /*readof previousthe word (backwards)punctuation. */
if \isMix(x) then leave;do j=#-1 by -1 call writeChar /*Foundread punctuation?some characters Then leavebackwards. */
end /*j*/ call rChar j /*read previous word (backwards). /* [↑] perform for "even" words.*/
if \datatype(x, 'M') then leave /*Found punctuation? Then leave J. */
call readLetters; call writeChar; #=punct /*read/write letters; new location*/
call wChar /*write a character (which is a letter)*/
end /*j*/ /* [↑] perform for "even" words. */
call rLett /*read letters until punctuation found.*/
call wChar; #= punct /*write a char; punctuation location. */
end /*until x==.*/
end /*case*/ /* [↑] process both of the input files. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isMixrLett: do until return \datatype( arg(1)x, 'M'); /*return call 1rChar; if argument is a letter.*/ end; return
readLetterswChar: docall charout until, \isMix(x); /*console*/; call readChar;charout oFID, x end/*file*/; return
writeChar: call charout , x; call charout oFID, x; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
readCharrChar: if arg(1)==''0 then do; x= charin(iFID); #= #+1; end /*read the next char*/
else x= charin(iFID, arg(1) ) ; /* " specific " */ return</syntaxhighlight>
{{out|output|text=&nbsp; when using the two (default) input files which contain:}}
return</lang>
'''output''' &nbsp; when using two (default) input files which contain:
:* &nbsp; input file &nbsp; '''ODDWORD.IN1''' &nbsp; ───► &nbsp; <tt> what,is,the;meaning,of:life. </tt>
:* &nbsp; input file &nbsp; '''ODDWORD.IN2''' &nbsp; ───► &nbsp; <tt> we,are;not,in,kansas;any,more. </tt>
Line 2,230 ⟶ 2,574:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Odd word problem
 
Line 2,274 ⟶ 2,618:
next
return cStr2
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,286 ⟶ 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,298 ⟶ 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,373 ⟶ 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.}}
<lang runbasic>open "oddWord.txt" for input as #f ' read input stream
<syntaxhighlight lang="runbasic">open "oddWord.txt" for input as #f ' read input stream
while not(eof(#f))
line input #f, a$
Line 2,406 ⟶ 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,426 ⟶ 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,433 ⟶ 2,779:
=={{header|Scheme}}==
Output is identical to python.
<langsyntaxhighlight lang="lisp">(define (odd)
(let ((c (read-char)))
(if (char-alphabetic? c)
Line 2,451 ⟶ 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,488 ⟶ 2,834:
until delimiter = '.';
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,501 ⟶ 2,847:
Recursive solution:
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func rev {
(var c = STDIN.getc) \\ return()
if (c ~~ /^[a-z]\z/i) {
Line 2,524 ⟶ 2,870:
l = false
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,537 ⟶ 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,549 ⟶ 2,895:
for {set coro f} {![eof stdin]} {} {
set coro [$coro [read stdin 1]]
}</langsyntaxhighlight>
Output is identical to Python and Scheme versions.
 
The only difference between the two coroutines (apart from the different names used when flipping back and forth) is the timing of the write of the character with respect to the recursive call.
 
=={{header|TUSCRIPT}}==
{{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,575 ⟶ 2,922:
PRINT outputstring
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,584 ⟶ 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,618 ⟶ 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,658 ⟶ 3,005:
Next
OddWordSecond = t
End Function</langsyntaxhighlight>
To call Functions :
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 2,670 ⟶ 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,679 ⟶ 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}}
<syntaxhighlight lang="wren">import "io" for Stdin,Stdout
import "./str" for Char
 
var fwrite = Fn.new { |ch|
System.write(ch)
Stdout.flush()
}
 
var doChar // recursive
doChar = Fn.new { |odd, f|
var c = Stdin.readByte()
if (!c) return false // end of stream reached
var ch = String.fromByte(c)
 
var writeOut = Fn.new {
fwrite.call(ch)
if (f) f.call()
}
 
if (!odd) fwrite.call(ch)
if (Char.isLetter(ch)) return doChar.call(odd, writeOut)
if (odd) {
if (f) f.call()
fwrite.call(ch)
}
return ch != "."
}
 
for (i in 0..1) {
var b = true
while (doChar.call(!b, null)) b = !b
Stdin.readByte() // remove \n from buffer
System.print("\n")
}</syntaxhighlight>
 
{{out}}
<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|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,696 ⟶ 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