Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type aliases and function signatures F#

Tags:

f#

I'm new in F# language, my profesional background is mostly C#/SharePoint and recently I went Haskell course which is lovely functional language.

My question is about usage of type aliases(synonyms) and function signatures, in Haskell is nice and straight way to do so like this:

type Person = (String,Int)
type Address = (Person, String,Int)

getPerson :: Address -> Person
getPerson n = first n ...

When I have tried the same in F# I'm sort of failed:

type Person = (int,int)
type Address = (Person, String, Int)

let getPerson (n:Address) =
    n.first ...

What did I do wrong? Or what is best practise to improve readability when I have function with signature (int, int) -> String -> int -> String -> (int, int) ?


The solution below as equivalent to Haskell type synonyms mentioned above:

type Person = int*int
type Address = Person * string * int

let first (n,_,_) = n

let getPerson (n:Address) : Person =
    first n
like image 247
Martin Bodocky Avatar asked Oct 31 '25 01:10

Martin Bodocky


1 Answers

The F# syntax for pairs is T1 * T2 and you can get the first element using the fst function (or using pattern matching), so a syntactically valid version of your code looks like this:

type Person = int * int
type Address = Person * string * int

let getPerson (n:Address) : Person =
    fst n

Have a look at F# for Fun and Profit - it is a great F# source and you can find all the syntax there.

Aside, note that type aliases in F# are really just aliases - so the compiler does not distinguish between Person and int * int. This also means that you might see both of them in the IntelliSense. If you want to distinguish between them more strongly, I'd recommend using a record or a single-case discriminated union (so that the type is actually a distinct type).

like image 178
Tomas Petricek Avatar answered Nov 02 '25 14:11

Tomas Petricek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!