简体   繁体   English

Haskell到F# - 在f#中声明一个递归类型

[英]Haskell to F# - declare a recursive types in f#

I am trying to teach my self F# by porting some Haskell Code. 我试图通过移植一些Haskell代码来教我自己的F#。

Specifily I am trying to port the Countdown Problem shown here 特别是我试图移植这里显示的倒计时问题

The Haskell Code is listed here 这里列出 Haskell代码

I am trying to create the following Haskell types in F#: 我试图在F#中创建以下Haskell类型:

data Op      = Add | Sub | Mul | Div

data Expr    = Val Int | App Op Expr Expr

In F# I think Op type is defined as follows: 在F#中我认为Op类型定义如下:

type Op = | Add | Sub | Mul | Div

I am having issues with the Expr type. 我遇到了Expr类型的问题。

How does one create a recursive type? 如何创建递归类型? From this SO question it looks like one can not create the Expr type in F#. 这个SO问题看起来,人们无法在F#中创建Expr类型。

Also what is the F# equivalent of 'App' type which apply s the Op type to the Expr type. 还有什么是'App'类型的F#等价物,它将Op类型应用于Expr类型。

If it is not possible to directly port this code, could someone suggest an alternative data structure. 如果无法直接移植此代码,有人可能会建议替代数据结构。

It's not a problem to define recursive types like this; 定义像这样的递归类型不是问题; what you can't do is create higher-kinded types, which are parameterized over type constructors (and which are not needed for this example). 你不能做的是创建更高级的类型,它们在类型构造函数上进行参数化(这个例子不需要它)。 With any union type definition, you need to separate the constructor name from the constructor parameters with the keyword "of", and the parameters themselves should take the form of a tuple type (ie they should be separated by asterisks): 对于任何联合类型定义,您需要使用关键字“of”将构造函数名称与构造函数参数分开,并且参数本身应采用元组类型的形式(即它们应以星号分隔):

type Op = Add | Sub | Mul | Div
type Expr = Val of int | App of Op * Expr * Expr

@kvb posted the right answer. @kvb发布了正确答案。

See also 也可以看看

F# forward type declarations F#转发类型声明

for how to do things when you do need mutually recursive types. 对于如何做的事情,当你确实需要相互递归类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM