In JavaScript, one would define a private member variable by making it a local variable in a function that returns a closure:
var count = (function(){
var i = 0;
return function (){ return i++; }
})();
This involves a define-function-then-call-it idiom that is fairly common in JavaScript, but I do not know how it translates in CoffeeScript. Any ideas?
You can use the do keyword
count = do ->
i = 0
-> i++
As Brian said, the do keyword is best. You can also use parens, just as in JavaScript:
count = (->
i = 0
-> i++
)()
Related
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.
I was taught, that data, by default, is immutable in F#.
When we reassign value to some variable, what really happens is that it rebinds the value of variable, but setting a new value is different thing.
Rebinding is called Shadowing whilst setting new value is impossible if we don't say explicitly, that value of the variable is mutable.
Can anyone explain to me this concept in a bit more details?
What is the difference between shadowing (rebinding):
let var = "new_value"
and setting a new value, as:
var <- "new_value"
Is this a moment, that during rebinding we create another object and we assign that object's address to the variable, whereas in the second example we change the value itself? I brought that from heap/stack concept.. but I may be wrong.
Thanks.
Shadowing is when you create a new binding that uses the same name as a previous binding. This "shadows" the original name, which hides it but doesn't change or replace it. Try this in FSI to see:
let foo = 42
let printFoo () =
printfn "%i" foo
printFoo() ;;
This will print:
42
val foo : int = 42
val printFoo : unit -> unit
val it : unit = ()
Then add:
// ... more code
let foo = 24
printfn "%i" foo // prints 24
printFoo ();;
This will print:
24
42
val foo : int = 24
val it : unit = ()
Note that it still prints 42 when you call printFoo() - the function sees the original (unshadowed) binding, but the new print shows the new value.
Using <- to mutate a value requires a mutable binding:
let mutable bar = 42
let printBar () =
printfn "%i" bar
printBar ();;
This, like above, prints 42. Note that you override the default immutable behavior here with the mutable keyword.
You then change the value within the mutable binding:
bar <- 24
printfn "%i" bar
printBar ();;
This will print 24 twice, since, unlike the shadowed version, the mutation changes the original binding. If you leave mutable off in the original binding, you'll get an error when using <-.
To add on Reed Copsey's excellent answer, if you're writing a loop where you change the value of an accumulator of some sort, you'd set the original value as mutable. For example, you can do this.
let mutable acc = 0 // declaration
for i in 1..100 do
acc <- acc + i // assignment
This is more or less equivalent to the C# code :
var acc = 0;
for (int i = 1; i <= 100; i++)
{
acc = acc + i; // assignment
// Another way to write this:
// acc += i;
}
However, in Shadowing, as in this F# snippet:
let acc = 0 // declaration
for i in 1..100 do
let acc = acc + i // another declaration only within the loop
You're not actually doing anything useful!! The second declaration has scope only within the for loop, and it doesn't change the value of the original acc.
A rough C# equivalent would be this:
var acc = 0; // declaration
for (int i = 1; i <= 100; i++)
{
var acc2 = acc + i; // another declaration only within the loop
}
Note that using acc (instead of acc2) for the inside variable wouldn't compile in C#, as it doesn't have Shadowing in this context.
The use of shadowing is that, it prevents from using the original variant in a block of code where you don't want it. So there is one less variable to worry about.
Whenever I wonder what actually is happening I use tools like ILSpy
For example:
let f () =
let x = Dictionary<int, string> ()
let mutable x = ResizeArray<int> 16
x <- ResizeArray<int> 16
Using ILSpy to decompile it in C# code it becomes:
public static void f()
{
Dictionary<int, string> x = new Dictionary<int, string>();
List<int> x2 = new List<int>(16);
x2 = new List<int>(16);
}
Here it's more obvious what the difference between shadowing and setting.
Shadowing x creates a new variable with name x2.
Setting is normal assignment.
I have the following function in F#:
let randomCh () =
let random = Random()
alph.Chars (random.Next (alph.Length - 1));
This function returns same value each time. I had same problem in C#, and solution very simple: create just one Random object like this:
var rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine(rnd.Next(10));
How can I reach same behaviour in F#: get each time random value?
Well your C# code doesn't define a function whereas your F# does; you could have the same problem in C#. You should either refactor your random definition out of the randomCh function, or bind randomCh to a function after initializing random:
let alph = "abcdefg"
let randomCh =
let random = Random()
fun () -> alph.Chars (random.Next (alph.Length - 1))
printfn "%O" <| randomCh()
printfn "%O" <| randomCh()
Just like in C#, you should pull the creation of the random outside of your function. This will prevent you from creating a new Random generator each call. By default, Random uses the current system clock to seed itself - if you call a function, with the random instance inside of it, quickly in succession, you can seed the random with the same time stamps, effectively giving you the same sequence.
By moving it outside of the function, you will reuse the same random instance, and avoid that:
let random = Random()
let randomCh () =
alph.Chars (random.Next (alph.Length - 1));
// Calling randomCh() repeatedly will now give different values each time
I am doing a small experiment in dart and I couldn't find a way to determine if a variable is "callable" without explicitly checking for each type (String, int, bool, ect) and guessing that it was callable if it was none of those. I also experimented with a try/catch which to me just seems wrong.
Whats the right way or at least the best way to make that determination?
Here is an example I did to show what I am trying to accomplish:
https://gist.github.com/digitalfiz/3f431dc07ca761389062
Use this function:
bool isCallable(v) => v is Function;
Usage Examples:
class Callable {
call() => 42;
}
void main() {
var foo = () => 42;
var bar = new Callable();
var baz = 42;
print(isCallable(foo)); //true
print(isCallable(bar)); //true
print(isCallable(baz)); //false
}
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.