Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

f#

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.

like image 773
TonyAbell Avatar asked Dec 16 '09 19:12

TonyAbell


2 Answers

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
like image 50
kvb Avatar answered Sep 27 '22 01:09

kvb


@kvb posted the right answer.

See also

F# forward type declarations

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

like image 31
Brian Avatar answered Sep 23 '22 01:09

Brian