Phunkie:PHP中的解析器組合(第1部分) >該教程改編自Inviqa博客,演示瞭如何使用PHP的Phunkie功能庫來創建Parser Compinators。 我們將重點介紹核心概念並建立基本的解析器,為更高級的組合者在隨後的一部分中奠定了基礎。
為什麼要為解析器進行功能編程?
解析是識別字符串中短語的過程。 我們將使用遞歸的解析,這是一種簡單而功能強大的技術。 組合器:組成功率 組合器是可重複使用的模式,用於組合功能。 在功能編程中,它們是從更簡單組件中構建複雜系統的基礎。 我們將實現解析器作為函數,並使用組合器將它們組合在一起。 的解析器
類型來表示此結果:一對包含匹配部分和剩餘的字符串。 要處理多個可能的匹配,我們將使用 >
原始解析器
,輸入字符串不變。
和 更優雅的
>
功能編程及其重點是純粹的功能和合成性,非常適合構建可靠和可維護的解析器。 將較小,定義明確的解析功能結合到較大,更複雜的能力是一個關鍵優勢。
Phunkie庫提供了必要的功能結構,以簡化此過程。
Pair
ImmList
Parser
<code class="language-php">use Phunkie\Types\Pair;
use Phunkie\Types\ImmList;
class Parser {
private $run;
public function __construct(callable $run) { $this->run = $run; }
public function run(string $toParse): ImmList { return ($this->run)($toParse); }
}</code>
:始終失敗,返回一個空列表。
)是單調模式的關鍵組成部分。 它允許鏈接計算,處理一個解析器的結果並將其傳遞到下一個。
result(string $a)
$a
<code class="language-php">function result(string $a): Parser {
return new Parser(fn(string $s) => ImmList(Pair($a, $s)));
}</code>
zero()
>解析器組合:<code class="language-php">function zero(): Parser {
return new Parser(fn($s) => Nil());
}</code>
item()
方法<code class="language-php">function item(): Parser {
return new Parser(fn(string $s) => strlen($s) == 0 ? Nil() : ImmList(Pair($s[0], substr($s, 1))));
}</code>
seq
seq
seq
>使用flatMap
和map
:<code class="language-php">use Phunkie\Types\Pair;
use Phunkie\Types\ImmList;
class Parser {
private $run;
public function __construct(callable $run) { $this->run = $run; }
public function run(string $toParse): ImmList { return ($this->run)($toParse); }
}</code>
或使用Phunkie的理解(0.6.0及以後):<code class="language-php">function result(string $a): Parser {
return new Parser(fn(string $s) => ImmList(Pair($a, $s)));
}</code>
以上是使用Phunkie的功能編程:PHP中的解析器組合器的詳細內容。更多資訊請關注PHP中文網其他相關文章!