F# Static Methods In Class - f#

I'm trying to figure out how to make static methods in a class in F#. Does anyone have any idea how to do this?

Sure, just prefix the method with the static keyword. Here's an example:
type Example = class
static member Add a b = a + b
end
Example.Add 1 2
val it : int = 3

If you wanted to have static methods in a static class, then use Module
Check out this link, in particular the Modules section:
http://fsharpforfunandprofit.com/posts/organizing-functions/
Here's a module that contains two functions:
module MathStuff =
let add x y = x + y
let subtract x y = x - y
Behind the scenes, the F#
compiler creates a static class with static methods. So the C#
equivalent would be:
static class MathStuff
{
static public int add(int x, int y)
{
return x + y;
}
static public int subtract(int x, int y)
{
return x - y;
}
}

Related

Mixing Up an Initializer and a Constructor Body in Dart

I know that you can initialize final variables in a class with something like:
class A {
final num x;
final num y;
final num d;
A(this.x, this.y):
d = sqrt(pow(x, 2) + pow(y, 2));
}
And you can create regular variables inside a constructor like this:
class A {
String z;
A(){
z = 'hello';
}
}
But how do you mix both? Is it possible? What is the syntax?
Simply continue with the constructor right after the initializer, but, since you're going to use curly brackets ({}), you shouldn't use the semi-colon (;):
class A {
final num x;
final num y;
final num d;
String z;
A(this.x, this.y)
: d = sqrt(pow(x, 2) + pow(y, 2))
{
z = 'hello';
}
}

What's the reasoning behind this colon in Dart

I'm checking out some dart code and looking at this:
AppState.fromJson(Map<String, dynamic> json)
: cartItems = (json['cartItems'] as List)
.map((i) => new CartItem.fromJson(i as Map<String, dynamic>))
.toList();
What's the reasoning behind the colon?
Why is this different from a regular assignment?
You can find more info in the dart tour: https://dart.dev/guides/language/language-tour#classes
If the superclass doesn’t have an unnamed, no-argument constructor, then you must manually call one of the constructors in the superclass. Specify the superclass constructor after a colon (:), just before the constructor body (if any).
Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.
// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, num> json)
: x = json['x'],
y = json['y'] {
print('In Point.fromJson(): ($x, $y)');
}
During development, you can validate inputs by using assert in the initializer list.
Point.withAssert(this.x, this.y) : assert(x >= 0) {
print('In Point.withAssert(): ($x, $y)');
}
You can also use them to initialize the final variables:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(x * x + y * y);
}

Clarification on mixins and implementations in Dart

In this article about Dart Mixins there is an example at the bottom:
class S {
twice(int x) => 2 * x;
}
abstract class I {
twice(x);
}
abstract class J {
thrice(x);
}
class K extends S implements I, J {
int thrice(x) => 3* x;
}
class B {
twice(x) => x + x;
}
class A = B with K;
The article goes on to say:
Now when we define A, we get the implementation of thrice() from K’s
mixin. However, the mixin won’t provide us with an implementation of
twice(). Fortunately, B does have such an implementation, so overall A
does satisfy the requirements of I, J as well as S.
I don't undrestand why B needs to implement twice. Why does K's thrice implementation get applied to B but its inherited twice implementation doesn't?
(Notice that the linked article is out-dated and does not apply to Dart 2.)
The idea behind mixins is that "a mixin" is the difference between a class and its superclass.
For the class K, that difference is everything in its declartion after the extends clause:
implements I, J {
int thrice(x) => 3* x;
}
When you then create a new class A by applying that mixin to a different class, B, as class A = B with K; then the resulting class becomes essentially:
class A extends B implements I, J {
int thrice(x) => 3* x;
}
This class implements the interfaces I and J, and has a twice method inherited from B and a thrice method mixed in from K.
(This example is not valid Dart 2. In Dart 2, you cannot extract an interface from a class declaration with a super-class other than Object. To declare a mixin that has a notion of a super-class, you must use the mixin declaration:
mixin K on S implements I, J {
int thrice(int x) => 3* x;
}
class B implements S {
int twice(int x) => 2 * x;
}
class A = B with K;
).

Implement F# interface via tacit programming

An idea from tacit programming is to not apply arguments to functions if it can be avoided.
Why doesn't F# allow this to compile if functions are first class members?
type IAdder =
interface
abstract member Add : int -> int -> int
end
type Adder =
interface IAdder with
member this.Add x y = x + y
type AdderWithInnerAdder(adder:IAdder) =
interface IAdder with
member this.Add = adder.Add
I get the compilation error...
No abstract property was found that corresponds to this override
I feel that this should compile. adder.Add clearly implements IAdder.Add and should be acceptable.
You can't assign interface members as if they were functions. Interfaces don't work like that. You have to specify the parameters:
member this.Add x y = adder.Add x y
But interfaces are generally bleh. They're only good for passing generic functions without losing genericity. When functions are non-generic, interfaces are strictly inferior.
If you were willing to go with a more functional approach instead, life would get easy fast:
type Adder = { Add: int -> int -> int }
let adder() = { Add = fun x y -> x + y }
let adderWithInnerAdder adder = { Add = adder.Add }

can I define struct in a class in F#?

this is example code in C# :
class exampleClass
{
struct exampleStruct
{
public int number;
}
private exampleStruct[,] e;
private enum exampleMove { Up, Down, Right, Left, Enter, Escape };
Stack<int> returnPath;
bool returntoBeg;
int numRandomMoves;
public exampleClass()
{
e = new exampleStruct[5, 5];
exampleStruct ex;
returntoBeg = false;
returnPath = new Stack<int>();
numRandomMoves = 0;
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
ex = new exampleStruct();
ex.number = 0
e[x, y] = ex;
}
}
}
}
I have an example code like above, i want to translate it into F#. But the problem is, when i make a class using F# and define struct in it, it shows errors and pointing that i can't declare type inside class type. Any help?
I think the following is a good workaround for nested types.
namespace MyNamespace
module private PrivateTypes =
[<Struct>]
type ExampleStruct(number: int) =
member __.Number = number
open PrivateTypes
type ExampleClass() =
let e = Array2D.init 5 5 (fun y x -> ExampleStruct(0))
//other members
ExampleStruct is nested under PrivateTypes, which is only visible in the same file.
While you cannot nest types, you can use intrinsic complex types that F# provides. Tuples are often a good data structure for data that has not very wide, observable scope, such as it is in your case.
In practice, I usually define implementation types in a module called e. g. Internal, and do not allow them to escape from the library. You may also define separate module per logical group of classes or even per complex class implementation.

Resources