Basics 02 - Basic Data Types and Signatures

Time to discuss the basic data types and signatures.

Learning-FSharp/Ch02-DataTypesAndSignatures/Program.fs

Check out all the comments that are placed in the source file.

Key Ideas

  1. Variables (values, actually) and functions are defined using let bindings

  2. To define a variable: let variableName = ...

  3. To define a function: let functionName param1 param2 = ...

  4. Variables created with let binding are immutable

  5. Use let mut binding to create mutable variables

  6. To define a mutable variable: let mut varName = ...

  7. To mutate the value: varName <- ...

  8. Immutability may seem like an odd idea, especially if you are coming from C++/C#/Java world

  9. Functional programming is mostly done with immutable variables; you will learn as we proceed

  10. F# compiler does an amazing job at identifying the types of variables

  11. In most cases decorating a variable name with the type (aka type declaration) isn't required

  12. The absence of type declaration with a variable doesn't mean it is type-less; F# is strictly typed

  13. The following statement results in the creation of an immutable int variable with value 10; the type is auto-detected based on assigned value: let x = 10

  14. To include type declaration: let y: int = 10

  15. Signed integer data types: sbyte, int16, int, int64

  16. Unsigned integer data types: byte, uint16, uint, uint64

  17. Boolean data type: bool

  18. Char and string: char and string

  19. 32-bit floating type: float32 or single

  20. 64-bit floating point: float or double

  21. Generic type: 'a or 'b or 'T; more on this later

  22. Absence of data: unit

  23. C++/C#/Java programmers tend to think of unit as void, which isn't the best idea

  24. Think of unit as an empty placeholder

  25. The unit data type has one possible value: ()

  26. Function signature: input type -> return type

  27. A function with more than one parameter: type1 -> type2 -> type3 -> return type

  28. A function with unit input: unit -> return type

  29. A function with unit output: input type -> unit

  30. A function with unit input/output: unit -> unit

  31. Both these functions have the signature: int -> int -> int

    1. No types declared: let add x y = x + y

    2. With types declared: let add (x: int) (y: int) : int = x + y

  32. Function call: let varName = funcName param1 param2 ... paramN

  33. Assume a function named F with signature unit -> int

  34. let varName: int = F () results in the invocation of F; The () in F () isn't similar to calling a void function in C++/C#/Java; Remember () is a value of type unit; () is the parameter passed to F

If you have reached so far, congratulations.

Keep reading!