Is there a standard naming convention for public values in modules? - f#

The F# code formatting guidelines give recommendations on usage of PascalCase and camelCase for the following:
camelCase for
values and functions that are
class-bound
expression-bound
pattern-bound
internal and private module-bound
parameters
public module-bound functions
PascalCase for
module names
type names
type members
discriminated union labels
namespaces
events
assembly names
It does not seem to say what to do for public-bound values (not functions) in a module, e.g.
module MyModule =
let aValue = ""
In F# Core, there are some examples of camelCase:
Set.empty, List.empty, Unchecked.defaultOf
But I've seen both used in the wild.

You can use either camelCase or PascalCase for public values in modules.
From p. 7 of the F# Component Design Guidelines (or Microsoft Docs):
Do use either PascalCase or camelCase for public functions and values in F# modules.

Related

In F#, what do you call a type defined as a function signature

In F#, is there a special name for a type defined in the following manner:
type Foo = int -> string
I ask because such a type seems to have special significance. It is quite abstract compared to other types and seems to only be usable as a sort of function interface. It is not discussed much in F# literature, but it is used quite a bit in the source of many F# OSS projects.
Is it a special sort of type that has some broader significance in functional programming? Does it have other applications other than functioning as a sort of interface for functions? Why is it something that doesn't really make sense to instantiate, even though you can kind of do that by defining a function with a matching type signature? Or is it really just as simple as saying that it is an alias for a function definition which can then be used as a short form in other type signatures/definitions and that accounts for all it's properties?
The name used in the F# documentation for this kind of definition is type abbreviation and I think many people often refer to it as type alias.
The definition defines an alias or a shorter name for a longer type. It says that whenever you type Foo, the compiler will see it as int -> string.
Type abbreviations do not define a new type, which means that Foo and int -> string are equivalent (a value of one type is also a value of the other type). The important points are:
Type inference will generally infer the original type, so when you write a function that matches the type, compiler will infer it as int -> string unless you give an explicit type annotation
When compiled, the abbreviations are erased (because .NET does not have such concept) and so the compiled code will see int -> string.
Abbreviations are useful just for readability reasons - it lets you use more descriptive name for a type. However, they do not have many other implications.

F# limitations of discriminated unions

I am trying to port a small compiler from C# to F# to take advantage of features like pattern matching and discriminated unions. Currently, I am modeling the AST using a pattern based on System.Linq.Expressions: A an abstract base "Expression" class, derived classes for each expression type, and a NodeType enum allowing for switching on expressions without lots of casting. I had hoped to greatly reduce this using an F# discriminated union, but I've run into several seeming limitations:
Forced public default constructor (I'd like to do type-checking and argument validation on expression construction, as System.Linq.Expressions does with it's static factory methods)
Lack of named properties (seems like this is fixed in F# 3.1)
Inability to refer to a case type directly. For example, it seems like I can't declare a function that takes in only one type from the union (e. g. let f (x : TYPE) = x compiles for Expression (the union type) but not for Add or Expression.Add. This seems to sacrifice some type-safety over my C# approach.
Are there good workarounds for these or design patterns which make them less frustrating?
I think, you are stuck a little too much with the idea that a DU is a class hierarchy. It is more helpful to think of it as data, really. As such:
Forced public default constructor (I'd like to do type-checking and argument validation on expression construction, as
System.Linq.Expressions does with it's static factory methods)
A DU is just data, pretty much like say a string or a number, not functionality. Why don't you make a function that returns you an Expression option to express, that your data might be invalid.
Lack of named properties (seems like this is fixed in F# 3.1)
If you feel like you need named properties, you probably have an inappropriate type like say string * string * string * int * float as the data for your Expression. Better make a record instead, something like AddInfo and make your case of the DU use that instead, like say | Add of AddInfo. This way you have properties in pattern matches, intellisense, etc.
Inability to refer to a case type directly. For example, it seems like I can't declare a function that takes in only one type from the
union (e. g. let f (x : TYPE) = x compiles for Expression (the union
type) but not for Add or Expression.Add. This seems to sacrifice some
type-safety over my C# approach.
You cannot request something to be the Add case, but you definitely do can write a function, that takes an AddInfo. Plus you can always do it in a monadic way and have functions that take any Expression and only return an option. In that case, you can pattern match, that your input is of the appropriate type and return None if it is not. At the call site, you then can "use" the value in the good case, using functions like Option.bind.
Basically try not to think of a DU as a set of classes, but really just cases of data. Kind of like an enum.
You can make the implementation private. This allows you the full power of DUs in your implementation but presents a limited view to consumers of your API. See this answer to a related question about records (although it also applies to DUs).
EDIT
I can't find the syntax on MSDN, but here it is:
type T =
private
| A
| B
private here means "private to the module."

Should I use Nullable<'a> or Option<'a> in F#?

Which way is more idiomatic to use Nullable<'a> or to use Option<'a> for representing a nullable int?
Option is far more idiomatic in F# code.
It has far nicer syntax when used in match and has large amounts of support from the standard library.
However, if you plan to access the code from C# or some other language you should probably expose the interface with Nullable which is easier to use in C#.
As John said, Option<T> is definitely more idiomatic type in F#. I would certainly use options as my default choice - the Option module provides many useful functions, pattern matching works nicely on options and F# libraries are generally designed to work with options.
That said, there are two cases when you might want to use nullable:
When creating arrays of optional values - Nullable<T> is a value type (sort of) and if you create an array Nullable<T>[] then it is allocated as continuous memory block. On the other hand options are reference types and option<T>[] will be an array of references to heap-allocated objects.
When you need to write some calculations and propagate missing values - in F# 3.0, there is a module Microsoft.FSharp.Linq.NullableOperators which implements various operators for dealing with nullable values (see MSDN documentation) which lets you write e.g.:
let one = Nullable(1)
let two = Nullable(2)
// Add constant to nullable, then compare value of two nullables
(one ?+ 2) ?>=? two

ObjectPascal identifier naming style on other languages

I learned to program with delphi, and i always liked the object pascal code style, looks very intuitive and clean.
When you look at the variable declaration, you know what are you dealing with..
A fast summary:
Exception E EMyError
Classes and Types T TMyClass
Fields in classes f fVisible
Events On OnMouseDown
Pointer types P PMyRecord
Property Get Something Set SetSomething
It's too bad to use this identifier naming style in C++ C# Java, or any other language code?
Aside from taste and cultural issues (as already pointed by Mason)
There might be reasons why a convention is tied to a certain language, and the other languages might also have reasons for theirs.
I can only quickly think of a few examples though:
On languages that don't require a pointer type to be defined before use (like most non-Borland Pascals, C etc), the "P" one is usually rarely necessary.
Other languages might also have additional means of disambiguating (like in C where often types are upper cased, and the variables or fields get the lowercase identifier), and does not need "T". (strictly speaking Delphi doesn't neither at least for fields, since identifiers are somewhat context dependantly looked up (likeseparate namespaces for fields and types), but the convention is older than that feature)
BTW, you forget "I" for interface, and enum names being prefixed with some prefix derived from the base type name (e.g.
TStringsDefined = set of (sdDelimiter, sdQuoteChar, sdNameValueSeparator,
sdLineBreak, sdStrictDelimiter)
)
etc.
Hmm, this is another language specific bit, since Object Pascal always adds enum names to the global space (instead of requiring enumtype.enumname). With a prefix there is less polution of the global space.
That is one of my pet peeves with Delphi btw, the lack of import control (Modula2 style IMPORT QUALIFIED , FROM xxx IMPORT. Extended Pascal also has some of this)
As far as I know, the T, E, F, and P prefixes are only commonly used in Delphi programming. They're a standard part of the idiom here, but in C# or Java they'd look out of place.
Get and Set are pretty standard across object-oriented programming. Not sure about the On prefix, but it wouldn't surprise me to find that that's common in any event-driven framework.

Which to use , abstract class or interface in F#?

Been grokking F# coming from a C# background.
In C# there is a clear difference in deciding when to use interfaces and when to use abstract classes. In F# I see the two blurring almost into one. I understand under the hood that the same is being done in F# as c# as far as the CLR is concerned, but what is the "best practise" when programming in F# to use?
Should I avoid class inheritance altogether?
I think that interfaces tend to be used much more frequently than abstract classes (compared to object-oriented languages like C#).
In many cases, you don't need any of the two, because you can just write higher-order function (that takes a function as an argument, instead of taking an interface as an argument). However, sometimes you may have two functions that are always used together - in that case, you can group two functions into an interface:
// Instead of using higher-order function
val foo : (int -> string) -> (string -> int) -> ...
// ..we can define an interface
type TwoWayConversion =
abstract ToString : int -> string
abstract FromString : string -> int
val foo : TwoWayConversion -> ...
I think that this is quite useful F# programming pattern that uses interfaces in a perfectly functional style.
On the other hand, I would use abstract classes only when writing object-oriented code that is supposed to be used from C# (e.g. C# code implementing your F# abstract class) - because that's a natural extensibility point from the C# point of view. However, I think that idiomatic F# code uses different extensibility points than C# (e.g. taking function/interface as an argument), so you don't really need abstract classes.
Well, if you're debating between abstract classes and interfaces, I think your reasons for one or the other would be the same as in C#.
Maybe you should consider using functions, functional data types and modules as units of abstraction though.
If you need to write an F# library to be used in C#, then you'll probably want to use interfaces etc for your exported types.

Resources