Addendum
Last updated
Was this helpful?
Last updated
Was this helpful?
š” Idea: reduce the calculation time of a function
ā How to: cache results ā next call with same arguments, return cached result
š In practice : function memoizeN
from library
ā ļø Caution : As with any optimization, use it when you need it and check (measure) that it works without any additional inconvenience.
ā Not to be confused with lazy
expression...
Syntax sugar to create a .NET Lazy<'T>
object from an expression
Expression not evaluated immediately but on 1st request ()
Interesting for improving performance without overcomplexifying the code
Lazy
active patternExtracts the value from a Lazy
object
3 ways to organize functions = 3 places to declare them:
Module: function declared within a module š
Nested : function declared inside a value or inside another function
š” Encapsulate helpers used just locally
ā Parent function parameters accessible to function nested
Method : function defined as a method in a type...
Defined with the member
keyword rather than let
Choice of the self-identifier: this
, me
, self
, _
...
Choice of the parameters style:
Tuplified: OOP style
Curried: FP style
Naming convention
camelCase
PascalCase
Currying
ā yes
ā if not tuplified nor overridden
Named parameters
ā no
ā if tuplified
Optional parameters
ā no
ā if tuplified
Overload
ā no
ā if tuplified
Parameter inference (declaration)
ā Possible
ā yes for this
, possible for the other parameters
Argument inference (usage)
ā yes
ā no, object type annotation needed
High-order function argument
ā yes
ā yes with shorthand member, no with lambda otherwise
inline
supported
ā yes
ā yes
Recursive
ā
yes with rec
ā yes
We can define a delegate in F# with the syntax:
type Fn = delegate of args: Args -> Return
š A delegate adds a thin layer on top of a function signature, like an object with a single method Invoke
:
Pros: we can use named arguments when invoking the delegate
Cons:
extra work to wrap the function (or the method) in the delegate and to execute the function by calling the Invoke(...)
method
cumbersome syntax when there are several parameters, to differentiate between tuple and curried parameters:
Tuple: type MyFn = delegate of (int * int) -> int
Curried: type MyFn = delegate of int * int -> int
It's not a very common use case in F#.
A .NET void
method is seen in F⯠as returning unit
.
Conversely, an F⯠function returning unit
is compiled into a void
method.
A .NET method with several arguments is "pseudo-tuplified":
All arguments must be specified (1)
Partial application of parameters is not supported (2)
Calls don't work with a real F⯠tuple ā ļø (3)
out
Parameter - In CāÆout
used to have multiple output values from a method
ā Ex : Int32.TryParse
, Dictionary<,>.TryGetValue
:
out
Parameter - In FāÆOutput can be consumed as a tuple š
new
?Compiler may not understand which overload is being called
Tips: call with named argument
Equivalent C# based on :