Haskell到F#-在F#中声明一个递归类型 [英] Haskell to F# - declare a recursive types in f#

查看:145
本文介绍了Haskell到F#-在F#中声明一个递归类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过移植一些Haskell代码来教自己的F#.

具体地说,我正在尝试移植显示的倒计时问题此处

列出了Haskell代码

我正在尝试在F#中创建以下Haskell类型:

data Op      = Add | Sub | Mul | Div

data Expr    = Val Int | App Op Expr Expr

在F#中,我认为Op类型的定义如下:

type Op = | Add | Sub | Mul | Div

我的Expr类型有问题.

如何创建递归类型?从这个SO问题中,您似乎无法在F#中创建Expr类型. /p>

同样,将Op类型应用于Expr类型的'App'类型在F#中的等效形式是什么.

如果无法直接移植此代码,则有人可以建议其他数据结构.

解决方案

定义这样的递归类型不是问题.您不能做的是创建类型更高的类型,这些类型通过类型构造函数进行参数化(此示例不需要).对于任何联合类型定义,您都需要使用关键字"of"将构造函数名称与构造函数参数分开,并且参数本身应采用元组类型的形式(即,它们应由星号分隔):

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

I am trying to teach my self F# by porting some Haskell Code.

Specifily I am trying to port the Countdown Problem shown here

The Haskell Code is listed here

I am trying to create the following Haskell types in F#:

data Op      = Add | Sub | Mul | Div

data Expr    = Val Int | App Op Expr Expr

In F# I think Op type is defined as follows:

type Op = | Add | Sub | Mul | Div

I am having issues with the Expr type.

How does one create a recursive type? From this SO question it looks like one can not create the Expr type in F#.

Also what is the F# equivalent of 'App' type which apply s the Op type to the Expr type.

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 (i.e. they should be separated by asterisks):

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

这篇关于Haskell到F#-在F#中声明一个递归类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆