Haskell to F# - declare a recursive types in f#

一个人想着一个人 提交于 2019-12-23 11:44:15

问题


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.


回答1:


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



回答2:


@kvb posted the right answer.

See also

F# forward type declarations

for how to do things when you do need mutually recursive types.



来源:https://stackoverflow.com/questions/1917091/haskell-to-f-declare-a-recursive-types-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!