最終課題:テキストパイプラインを移植する
Coddyの「Lua開発者のためのPHP」コースのレッスン 47/48。
チャレンジ
簡単入力は文字列のリストです。このタスクで提供されている参照プログラムを移植してください。abbreviations は空文字列を取り除き、残った各文字列の最初の ASCII 文字を取得して大文字にし、ドットで結合します。順序を保ち、空でない文字列がない場合は none を返します。入力はすべて ASCII です。
提供されているメインスクリプトは標準入力から JSON 値を1つ読み込み、指定された公開 API を確認して、結果を出力します。出力せずにモジュール宣言を実装してください。ランチャーを置き換えたり、モジュールから入力を読み込んだりしないでください。入力は指定された型と範囲を満たしています。
Functions.php を編集してください。main.php はロックされたエントリーファイルです。依存関係には相対ファイル名とともに require_once __DIR__ を使用します。
Lua の参照プログラム
local function abbreviations(words)
local parts={}
for _,word in ipairs(words) do
if #word>0 then
local first=string.byte(word,1)
if first>=97 and first<=122 then first=first-32 end
parts[#parts+1]=string.char(first)
end
end
return #parts==0 and "none" or table.concat(parts,".")
end
print(abbreviations({"red","","green","blue"}))
自分で試してみよう
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(abbreviations(["a","","b"])==="A.B" && abbreviations([])==="none","port pipeline");
echo abbreviations($input),"\n";
Lua開発者のためのPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ