首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在FSYACC中使用记录类型

在FSYACC中使用记录类型
EN

Stack Overflow用户
提问于 2015-04-16 12:32:36
回答 1查看 105关注 0票数 1

在FSYACC中,通常会有导致元组的终端。但是,为了方便起见,我想使用记录类型。例如,如果在抽象语法树(AbstractSyntaxTree.fsl)中有以下内容:

代码语言:javascript
复制
namespace FS
module AbstractSyntaxTree =

 type B = { x : int; y : int }

 type Either = 
      | Record of B
      | Tuple of int * string

 type A =
     | Int of int
     | String of string
     | IntTuple of Either

我不清楚FSYACC (parser.fsy)中正确的语法,因为如果我使用:

代码语言:javascript
复制
%start a
%token <string> STRING
%token <System.Int32> INT
%token ATOMTOKEN TUPLETOKEN EOF
%type < A > a

%%

a:
    | atomS { $1 }
    | atomI { $1 }
    | either { $1 }

atomI:
    | ATOMTOKEN INT   { Int($2) }

atomS:
    | ATOMTOKEN STRING { String($2)  }

either:
    | TUPLETOKEN INT INT { Record {x=$2;y=$3} } // !!!
    | TUPLETOKEN TUPLETOKEN INT STRING { Tuple( $3, $4) } // !!!

我希望可以推断出B类型和元组。但是,FSYACC给出了标记为“!”的两行的错误:

代码语言:javascript
复制
This expression was expected to have type  A but here has type Either

对于最后两行的“任一”产品,正确的语法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-16 14:00:07

你不是指IntTuple($2, $3)而不是B($2, $3)吗?我想试试IntTuple{x=$2; y=$3}

编辑:工作:

代码语言:javascript
复制
module Ast

type B = { x : int; y : int }
type A =
    | Int of int
    | String of string
    | IntTuple of B

代码语言:javascript
复制
%{

open Ast

%}

%start a
%token <string> STRING
%token <System.Int32> INT
%token ATOMTOKEN TUPLETOKEN 
%type < Ast.A > a


%%

a:
    | atom { $1 }
    | tuple { $1 }

atom:
    | ATOMTOKEN INT   { Int($2) }
    | ATOMTOKEN STRING { String($2) }

tuple:
    | TUPLETOKEN INT INT { IntTuple {x = $2; y = $3} }

编辑2:非常小心,行%type < Ast.A > a要求您的非终端aAst.A类型。因此,由于您直接使用非终端tuple,所以tuple需要类型为Ast.A。因此,您必须用IntTuple包装记录,所以语法是IntTuple {x = $2; y = $3},而不是{x = $2; y = $3}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29674841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档