Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring internal types in F#

Tags:

types

f#

Recently I came across a code listing like so:

type MyType =
  | MyType of int

and internal MyInternal =
  | One of MyType
  | Two of MyType

I am not familiar with the usage of 'and internal' (on the third line) and I was wondering if there was any difference between using 'type internal' like this:

type MyType =
  | MyType of int

type internal MyInternal =
  | One of MyType
  | Two of MyType

I have experimented with both forms briefly, and I can't see a difference. Is this just two different ways to write the same thing?

like image 969
A.R. Avatar asked Jun 10 '13 20:06

A.R.


People also ask

Can I define my own object types in F code?

You can define your own object types just as you can in any other.NET language. Also, F# code can define aliases, which are named type abbreviations, that are alternative names for types. You might use type abbreviations when the type might change in the future and you want to avoid changing the code that depends on the type.

What are the different types in F #?

Generally, the types in F# can be grouped into the following categories: Common .NET types. These are types that conform to the .NET Common Language Infrastructure (CLI), and which are easily portable to every .NET language.

What are the different types of functions in the F #library?

Many of these types have associated modules in the F# library that support common operations on these types. The type of a function includes information about the parameter types and return type. The .NET Framework is the source of object types, interface types, delegate types, and others.

Can I access the types created in module1 from module2?

Therefore, there are two modules, Module1 and Module2. A private type and an internal type are defined in Module1. The private type cannot be accessed from Module2, but the internal type can. The following code tests the accessibility of the types created in Module1.fs.


2 Answers

In this instance, the and keyword would be used to define mutally recursive types MyType and MyInternal. Since MyType and MyInternal are not mutually recursive, the and is not required.

As the MSDN page states:

The and keyword replaces the type keyword on all except the first definition

so the definitions are equivalent.

like image 93
Lee Avatar answered Oct 06 '22 01:10

Lee


No, your suggested code is definitely more idiomatic.

type T = ...
and U = ...

is typically only used if the types are mutually recursive. Using it with an internal type would be even more strange, since the constructors of the first type would also need to be made internal:

type T = internal | T of U
and internal U = | U of T
like image 34
kvb Avatar answered Oct 05 '22 23:10

kvb