解釋器(Interpreter)

意圖

給定一個語言,定義它的文法的一種表示,并定義一個解釋器,這個解釋器使用該表示來解釋語言中的句子。

結構

解釋器的結構圖

動機

如果一種特定類型的問題出現的頻率足夠高,那么可能值得將問題的各個部分表述為一個簡單語言中的句子。這樣就可以構建一個解釋器,該解釋器通過解釋這些句子來解決這類問題。

解釋器模式描述了如何為簡單的語言定義一個文法,如何在該語言中表示一個句子,以及如何解釋這些句子。

適用性

當有一個語言需要解釋執行,并且語言中的句子能表示為抽象語法樹時,可以使用解釋器模式。

注意事項

  • 解釋器模式并沒有解釋如何創建一個抽象語法樹,也就是說,它不涉及到語法分析;
  • 解釋器表達式不一定要定義解釋操作,或者也可以將解釋操作委托給一個“訪問者”(Visitor)對象,避免在各個表達式中繁瑣地定義這些操作;
  • 終結表達式可以用享元模式(Flyweight)共享。


示例一

問題

定義一個正則表達式,用于檢查一個字符串是否匹配。正則表達式的文法定義如下:

  1. expression ::= liternal | alternation | sequence | repetition | '(' expression ')'
  • alternation ::= expression '|' expression
  • sequence ::= expression '&' expression
  • **repetition := expression '*' **
  • liternal := 'a' | 'b' | 'c'| ... { 'a' | 'b' | 'c' | ...}*

創建:
"raining" & ( "dogs" | "cats") *

輸入:
rainingcatscats

輸出:
true

實現(C#)

為了實現這個簡易的正則表達式解析器,我們定義了如下幾個表達式類:

正則表達式解析器
// 正則表達式的抽象基類
public abstract class  RegularExpression
{
    public abstract string Match(string input);
}
// 字面表達式
public sealed class LiternalExpression : RegularExpression
{
    private readonly string liternal;

    public LiternalExpression(string liternal)
    {
        this.liternal = liternal;
    }

    public override string ToString()
    {
        return  "\""+ liternal + "\"";
    }

    public override string Match(string input)
    {
        if(!input.StartsWith(liternal)) 
            return input;
        else
            return input.Substring(liternal.Length);
        
    }
}
// 或操作表達式
public sealed class AlternationExpression : RegularExpression
{
    private readonly RegularExpression left;
    private readonly RegularExpression right;

    public AlternationExpression(RegularExpression left, RegularExpression right)
    {
        this.left = left;
        this.right = right;
    }

    public override string ToString()
    {
        return string.Format("({0} | {1})", left.ToString(), right.ToString());
    }

    public override string Match(string input)
    {               
        var rest = left.Match(input);
        return rest == input ? right.Match(input) : rest;
    }
}
// 與操作表達式
public sealed class SequenceExpression : RegularExpression
{
    private readonly RegularExpression left;
    private readonly RegularExpression right;

    public SequenceExpression(RegularExpression left, RegularExpression right)
    {
        this.left = left;
        this.right = right;
    }

    public override string ToString()
    {
        return string.Format("({0} & {1})",left.ToString(),right.ToString());
    }

    public override string Match(string input)
    {       
        var rest = left.Match(input);

        if(rest != input) return right.Match(rest);

        return rest;
    }
}

// 重復操作表達式
public sealed class RepetitionExpression : RegularExpression
{
    private readonly RegularExpression repetition;

    public RepetitionExpression(RegularExpression repetition)
    {
        this.repetition = repetition;
    }

    public override string ToString()
    {
        return string.Format("{0} *", repetition.ToString());
    }

    public override string Match(string input)
    {
        var repetition2 = repetition;
        var rest = repetition2.Match(input);
        while(rest != input) 
        {
            if(!(repetition2 is LiternalExpression))
            {
                repetition2 = new LiternalExpression(input.Substring(0,input.Length - rest.Length));
            } 

            input = rest;
            rest = repetition2.Match(input);
        }

        return rest;
    }
}
// 測試!注意添加命名空間: using System;
public class App
{
    public static void Main(string[] args)
    {
        // "raining" & ( "dogs" | "cats") *
        LiternalExpression raining = new LiternalExpression("raining");
        LiternalExpression dogs = new LiternalExpression("dogs");
        LiternalExpression cats = new LiternalExpression("cats");

        AlternationExpression dogsOrCats = new AlternationExpression(dogs,cats);
        RepetitionExpression repetition = new RepetitionExpression(dogsOrCats);
        SequenceExpression sequence = new SequenceExpression(raining,repetition);

        //打印出正則表達式的結構
        Console.WriteLine(sequence.ToString());

        Console.WriteLine("input = \"{0}\", result = {1}",
                "rainingcatscats", 
                sequence.Match("rainingcatscats") == string.Empty);
        Console.WriteLine("input = \"{0}\", result = {1}",
                "rainingdogsdogs", 
                sequence.Match("rainingdogsdogs") == string.Empty);
        Console.WriteLine("input = \"{0}\", result = {1}",
                "rainingCatsCats", 
                sequence.Match("rainingCatCats") == string.Empty);
    }
}

// 控制臺輸出:
//  ("raining" & ("dogs" | "cats") *)
//  input = "rainingcatscats", result = True
//  input = "rainingdogsdogs", result = True
//  input = "rainingCatsCats", result = False

示例二

問題

實現對布爾表達式進行操作和求值。文法定義如下:

  1. boolean ::= Variable | Constant | Or | And | Not | '(' boolean ') '
  • Or ::= boolean '|' boolean
  • And ::= boolean '&' boolean
  • Not := '!' boolean
  • Constant := 'true' | 'false'
  • **Variable := 'A' | 'B' | ... | 'X' | 'Y' | 'Z' **

創建:
( true & X ) | ( Y & ( !X ) )

輸入:
X = fase, Y = true

輸出:
true

實現(C#)

同樣,我們先設計出相關表達式的結構圖:

布爾表達式結構圖
// 布爾表達式的抽象基類
public abstract class BooleanExpression
{
    public abstract bool Evaluate(Context context);
}
// 常量表達式
public sealed class ConstantExpression : BooleanExpression
{
    private readonly bool val;

    public ConstantExpression(bool val)
    {
        this.val = val;
    }

    public override bool Evaluate(Context context)
    {
        return this.val;
    }

    public override string ToString()
    {
        return val.ToString();
    }
}
// 與操作表達式
public sealed class AndExpression : BooleanExpression
{
    private readonly BooleanExpression left;
    private readonly BooleanExpression right;

    public AndExpression(BooleanExpression left, BooleanExpression right)
    {
        this.left = left;
        this.right = right;
    }

    public override bool Evaluate(Context context)
    {
        return this.left.Evaluate(context) && this.right.Evaluate(context);
    }

    public override string ToString()
    {
        return string.Format("({0} & {1})", left.ToString(), right.ToString());
    }
}
// 或操作表達式
public sealed class OrExpression : BooleanExpression
{
    private readonly BooleanExpression left;
    private readonly BooleanExpression right;

    public OrExpression(BooleanExpression left, BooleanExpression right)
    {
        this.left = left;
        this.right = right;
    }

    public override bool Evaluate(Context context)
    {
        return this.left.Evaluate(context) || this.right.Evaluate(context);
    }

    public override string ToString()
    {
        return string.Format("({0} | {1})", left.ToString(), right.ToString());
    }
}
// 非操作表達式
public sealed class NotExpression : BooleanExpression
{
    private readonly BooleanExpression expr;

    public NotExpression(BooleanExpression expr)
    {
        this.expr = expr;
    }

    public override bool Evaluate(Context context)
    {
        return !this.expr.Evaluate(context);
    }

    public override string ToString()
    {
        return string.Format("(!{0})", expr.ToString());
    }
}
// 變量表達式
public class VariableExpression : BooleanExpression
{
    private readonly string name;

    public VariableExpression(string name)
    {
        this.name = name;
    }

    public override bool Evaluate(Context context)
    {
        return context.Lookup(this);
    }

    public string Name { get { return this.name;} }

    public override string ToString()
    {
        return this.name;
    }
}
// 操作上下文
public class Context
{
    private readonly Dictionary<VariableExpression,bool> map = new Dictionary<VariableExpression,bool>();

    public void Assign(VariableExpression expr,bool value)
    {
        if(map.ContainsKey(expr))
        {
            map[expr] = value;
        }
        else
        {
            map.Add(expr, value);
        }
    }

    public bool Lookup(VariableExpression expr)
    {
        return map[expr];
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();

        foreach(KeyValuePair<VariableExpression,bool> kvp in map)
        {
            sb.AppendFormat("{0}={1},", kvp.Key.Name, kvp.Value);
        }

        return sb.ToString();
    }
}
// 測試。注意添加命名空間:
//     using system;
//     using System.Text;
//     using System.Collections.Generic;
public class App
{
    public static void Main(string[] args)
    {
        Context context = new Context();
        VariableExpression X = new VariableExpression("X");
        VariableExpression Y = new VariableExpression("Y");

        // ( true & X ) | ( Y & ( !X ) )
        BooleanExpression expr = new OrExpression(
                    new AndExpression(new ConstantExpression(true), X),
                    new AndExpression(Y, new NotExpression(X))
                );

        context.Assign(X,false);
        context.Assign(Y,true);

        Console.WriteLine("Expression : {0}", expr.ToString());
        Console.WriteLine("   Context : {0}", context.ToString());
        Console.WriteLine("    Result : {0}", expr.Evaluate(context));

    }
}
// 控制臺輸出:
//  Expression : ((True & X) | (Y & (!X)))
//      Context : X=False,Y=True,
//      Result : True
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • 1 場景問題# 1.1 讀取配置文件## 考慮這樣一個實際的應用,維護系統自定義的配置文件。 幾乎每個實際的應用系...
    七寸知架構閱讀 3,154評論 2 56
  • 第5章 引用類型(返回首頁) 本章內容 使用對象 創建并操作數組 理解基本的JavaScript類型 使用基本類型...
    大學一百閱讀 3,270評論 0 4
  • 用法: apt-cache [選項] 命令 apt-cache [選項] showpkg 軟件包1 [軟件包2 ....
    夜觀星閱讀 864評論 0 0
  • 大徐是小白的初戀男友,卻是她從來不愿意承認的戀人,爽朗大方如小白,每次吃飯時只要有人敢不怕死的提起他們的戀愛史,總...
    陶瓷兔子閱讀 2,925評論 15 91