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.
Related
I trying make the following overloading inside my class:
class Array extends ListBase<double> {
List<double> l = [];
List<double> operator +=(List<double> b) {
var c = Array.length(l.length);
for(int i = 0; i < l.length; i++) {
c[i] = this[i] * b[i];
}
return c;
}
}
but the Dart compiler show the error message: the string '+=' ins't a user-definable operator. Is there some way to make the overloading of the operator += for others classes types?
Overload only operator +. Dart reuse operators that have a well known semantic meaning such as +=.
Add #override annotation if operator already defined in base class.
seq is an alias of the IEnumerable interface, then you can create objects which implements IEnumerable and use its methods, for example:
IEnumerable<int> list = new List<int> { 1, 2, 3, 4, 5 };
and use the IEnumerable methods:
Where, Max, etc.
But you must instance an object that implements IEnumerable.
But... in F# you can create a sequence like:
let list = seq { for i in 1..5 -> i }
And Visual Studio says you list has the seq type. This is impossible, seq is an interface (IEnumerable) and you can't create an instance of an interface.
So, what's the magic inside seq?
Using GetType in FSI:
let goingToSee = seq { for i in 1..5 -> i }
goingToSee.GetType();;
val goingToSee : seq<int>
val it : System.Type = FSI_0010+goingToSee#12
The seq { .. } expression in F# is more similar to iterator methods in C# (written using the yield keyword) than to collection initializers. Similarly to the C# compiler handling of iterators, F# compiler turns the seq { .. } expression into a class that implements IEnumerable<T>.
The compiled class inherits from GeneratedSequenceBase (see the source code) and puts code generated based on what you wrote in the sequence expression. It is compiled as a state machine, so the code looks a bit ugly, but if you look at it using ILSpy, it looks something like this:
internal sealed class list#6 : GeneratedSequenceBase<int> {
public override int GenerateNext(ref IEnumerable<int> next) {
switch (this.pc) {
case 1: goto IL_82;
case 2: this.i = 0; break;
case 3: goto IL_A3;
default: {
this.#enum = Operators.OperatorIntrinsics.RangeInt32(1, 1, 5).GetEnumerator();
this.pc = 1;
break; }
}
if (this.#enum.MoveNext()) {
this.i = this.#enum.Current;
this.pc = 2;
this.current = this.i;
return 1;
}
IL_82:
this.pc = 3;
LanguagePrimitives.IntrinsicFunctions.Dispose<IEnumerator<int>>(this.#enum);
this.#enum = null;
this.pc = 3;
IL_A3:
this.current = 0;
return 0;
}
}
I will not try to decode this, but I think pc keeps the state of the state machine. Depending on this, it either initializes the iterator, moves to the next state, or disposes of any resources that might be used.
It's also worth noting that the 6 in the name list#6 is the line number from where this generated class comes from.
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 }
I need clarity on how objects are declared and assigned a definition in F#.
What's happening in this code?
let service = {
new IService with
member this.Translate(_) = raise error }
My guess is we're creating an object that will implement some interface on the fly even though there is no actual class that's backing this object. Hence, we're removing the ceremony involved with creating an object by not having to declare a separate class to use it. In this case, we're minimizing the ceremony involved for implementing a mock object that could be used within a unit test.
Is my understanding accurate?
I tried to research my question and found the specification for F# 3.0 (Section - 6.3.8 Object Expressions)
6.3.8 Object Expressions An expression of the following form is an object expression: { new ty0 args-expropt object-members interface
ty1 object-members1 … interface tyn object-membersn } In the case
of the interface declarations, the object-members are optional and are
considered empty if absent. Each set of object-members has the form:
with member-defns endopt Lexical filtering inserts simulated $end
tokens when lightweight syntax is used. Each member of an object
expression members can use the keyword member, override, or default.
The keyword member can be used even when overriding a member or
implementing an interface.
For example:
let obj1 =
{ new System.Collections.Generic.IComparer<int> with
member x.Compare(a,b) = compare (a % 7) (b % 7) }
You can get a pretty good picture of what is happening behind the scenes if you look at the generated IL using a decompiler like ILSpy. For the example involving IComparer, it generates a hidden class, which implements the interface:
internal sealed class obj1#2 : IComparer<int> {
public obj1#2() : this() { }
int IComparer<int>.System-Collections-Generic-IComparer(int x, int y) {
int num = x % 7;
int num2 = y % 7;
if (num < num2) { return -1; }
return (num > num2) ? 1 : 0;
}
}
Inside the body of the method, it then creates a new instance:
IComparer<int> obj1 = new obj1#2();
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;
}
}