phramework/expression-parser

LISP 类的表达式解析器

v0.1.0 2022-05-12 14:04 UTC

This package is auto-updated.

Last update: 2024-09-12 19:37:46 UTC


README

一个用于评估表达式的 "LISP 类" 表达式解析器 构建状态 覆盖率状态

要求

安装

使用 composer 安装包

composer require phramework/expression-parser

使用示例

定义简单的语言

<?php
/*
 * Define a language
 * with a Boolean function "or"
 */
$language = (new Language())
    /*
     * Define 'or' function
     */
    ->set(
        'or',
        function(bool $l, bool $r) : bool {
            return $l || $r;
        }
    );

/*
 * Create an expression parser based on the language
 */
$parser = new ExpressionParser(
    $language
);

/*
 * Evaluate an expression, expect result to be true
 */
$result = $parser->evaluate([
    'or', // first argument is always the function name 
    true, // will be passed as or function's first argument
    false // will be passed as or function's second argument
]);

更复杂的示例

<?php
/*
 * Define a language
 * with "+" (addition) and "-" (subtraction) functions for float numbers
 */
$language = (new Language())
    /*
     * Define "+" (addition) function
     */
    ->set(
        '+',
        function(float $l, float $r) : float {
            return $l + $r;
        }
    )
    /*
     * Define "-" (subtraction) function
     */
    ->set(
        '-',
        function(float $l, float $r) : float {
            return $l - $r;
        }
    );

/*
 * Create an expression parser based on the language
 */
$parser = new ExpressionParser(
    $language
);

/*
 * Evaluate expression
 * expect result to be 5 + (4.5 - 1) = 8.5
 */
$result = $parser->evaluate([
    '+',
    5,
    [
        '-',
        4.5,
        1
    ],
]);

开发

安装 composer 依赖项

composer update

运行测试

composer test

许可证

版权 2016-2018 Xenofon Spafaridis

根据 Apache 许可证版本 2.0("许可证")授权;除非适用法律要求或经书面同意,否则不得使用此文件,除非符合许可证规定。您可以在以下位置获得许可证副本:

https://apache.ac.cn/licenses/LICENSE-2.0

除非适用法律要求或经书面同意,否则根据许可证分发的软件按"现状"提供,不提供任何明示或暗示的保证或条件。有关许可证的具体语言、权限和限制,请参阅许可证。