F# How do I access a member from a function - function

I'm pretty new to F# so I'm not quite sure what I'm doing wrong here
here's what I'm trying to do:
type MyClass() =
let someVar = this.MyMember()
member this.MyMember() :unit =
// insert some code here
I can't do that because Visual Studio tells me that "this" isn't defined
so what should I do?
am I missing some obvious feature of F# or something?
I tried making all my members functions instead... but then I'd have to re-order all the functions so they become visible and then it still wouldn't work
so what do?

You need to insert a self-identifier. This is not done by default for some performance reasons.
The following works:
type MyClass() as this =
let someVar = this.MyMember()
member this.MyMember() :unit = ()

Related

Understanding cyclomatic complexity

I have some piece of code that basically looks like this:
public MyObject getData(boolean someFlag) {
String select1 = "SELECT * FROM myTable WHERE someInteger = ?";
SqlHostvariablen hostvars = new SqlHostvara();
hostvars.addInteger(myField.getSomeInteger);
String[][] selarray = SqlHelper.doSelectAsMatrix(select1, hostvars);
if (selarray.length == 0) {
throw new IllegalArgumentException("Nothing found");
}
MyObject foo = new MyObject();
int i = 0;
foo.setSomething1(selarray[0][i++]);
foo.setSomething2(selarray[0][i++]);
foo.setSomething3(selarray[0][i++]);
foo.setSomething4(selarray[0][i++]);
foo.setSomething5(selarray[0][i++]);
foo.setSomething6(selarray[0][i++]);
foo.setSomething7(selarray[0][i++]);
foo.setSomething8(transformSomething8(selarray[0][i++]));
foo.setSomething9(selarray[0][i++]);
foo.setSomething10(selarray[0][i++]);
String someValue1 = selarray[0][i++];
String someValue2 = selarray[0][i++];
foo.setSomething11(selarray[0][i++]);
doSomethingWithFoo(foo, someFlag, someValue1, someValue2);
doSomethingElseWithFoo(foo);
return foo;
}
The identifiers and SQL statement are anonymized but otherwise my method looks the same.
Now Checkstyle claims that the cyclomatic comlexity if this method is 12. I always thought I knew what CC was and from my knowledge I'd say this methods CC is 2. There is one if that creates a new path through the code and the control flow graph therefore has 2 paths/exit points. I don't see where else there should be a path through the code.
Am I missing something entirely or is Checkstyle just wrong?
Turned out this was a Checkstyle error. While not even cleaning the problem did the trick, after a system restart the warning was gone. An Eclipse restart might have been enough, no way to know for sure.

Seperate Function Decleration and Implementation in F# [duplicate]

I'm a bit confused as to how to get two method to call each other (i.e., have A() call B() and B() call A()). It seems that F# only 'sees' the method after it's been encountered in code, so if it hasn't, it just says value or constructor has not been defined.
Am I missing something very basic here?
'let rec... and...' is the syntax you seek.
let rec F() =
G()
and G() =
F()
See also Adventures in F# Co-Recursion.
Since the question is about methods, and Brian's answer is about functions, maybe it's useful to point out that you can use a similar syntax for types:
type A() =
let b = new B()
member x.MethodA() = b.MethodB()
and B() =
member x.MethodB() = ()
Note also that members are 'let rec' by default (in fact I don't think they can be not recursive).
F# 4.1 introduces mutually recursive modules and namespaces.
These are an alternative to the and keyword.
module rec PingPong = // <------ rec keyword here.
let pong() =
printfn "pong"
ping()
let ping () =
printfn "ping"
pong()
The rec keyword defines modules and namespaces that "allow for all contained code to be mutually recursive."
Functions declared via let
let rec a () = b ()
and b () = ()
These are mutually recursive functions.
Methods within the same type
type T () =
member t.A () = t.B()
member t.B () = ()
This is trivial; it just works. Note Abel's comment though.
Methods within different types
type TypeA () =
member t.A (b : TypeB) = b.B()
and TypeB () =
member b.B () = ()
This uses the type ... and syntax for mutually recursive types.
Notes
Normally, and is only used if the calls occur in both directions. Otherwise, it may be better to re-order the declarations so that the called function comes first. It is often helpful for type-inference and readability to avoid circular dependencies, and to not imply them where they aren't used.
I propose to edit the question to either ask for functions in general, or to ask for different types (in which case I would remove the first two cases from this answer). Methods are usually considered to be a subset of functions, which is the general mathematical term. However, all F# functions are technically CLI methods, as that is what they are compiled to. As is, it is not clear what the question is asking for, but I assume from the accepted answer that it does not only ask for methods, as the title would imply.

MATLAB: Is there a method to better organize functions for experiments?

I will run a set of experiments. The main method evaluated has the following signature:
[Model threshold] = detect(...
TrainNeg, TrainPos, nf, nT, factors, ...
removeEachStage, applyEstEachStage, removeFeatures);
where removeEachStage, applyEstEachStage, and removeFeatures are booleans. You can see that if I reverse the order of any of these boolean parameters I may get wrong results.
Is there a method in MATLAB that allows better organization in order to minimize this kind of error? Or is there any tool I can use to protect me against these errors?
Organization with a struct
You could input a struct that has these parameters as it's fields.
For example a structure with fields
setts.TrainNeg
.TrainPos
.nf
.nT
.factors
.removeEachStage
.applyEstEachStage
.removeFeatures
That way when you set the fields it is clear what the field is, unlike a function call where you have to remember the order of the parameters.
Then your function call becomes
[Model threshold] = detect(setts);
and your function definition would be something like
function [model, threshold] = detect(setts)
Then simply replace the occurrences of e.g. param with setts.param.
Mixed approach
You can also mix this approach with your current one if you prefer, e.g.
[Model threshold] = detect(in1, in2, setts);
if you wanted to still explicitly include in1 and in2, and bundle the rest into setts.
OOP approach
Another option is to turn detect into a class. The benefit to this is that a detect object would then have member variables with fixed names, as opposed to structs where if you make a typo when setting a field you just create a new field with the misspelled name.
For example
classdef detect()
properties
TrainNeg = [];
TrainPos = [];
nf = [];
nT = [];
factors = [];
removeEachStage = [];
applyEstEachStage = [];
removeFeatures =[];
end
methods
function run(self)
% Put the old detect code in here, use e.g. self.TrainNeg to access member variables (aka properties)
end
end

LINQ to SQL Projection: Func vs Inline

I am finding some unexpected behavior when using a projection in a LINQ to SQL query using a Func. Example code will explain better than words.
A basic L2S lambda query using projection:
db.Entities.Select(e => new DTO(e.Value));
It translates to the desired SQL:
SELECT [t1].[Value]
FROM [Entity] AS [t1]
However, when the projection is put into a Func like this:
Func<Entity, DTO> ToDTO = (e) => new DTO(e.Value);
And called like this:
db.Entities.Select(e => ToDTO(e));
The SQL is now pulling back all of the columns in the table, not just the one in the projection:
SELECT [t1].[Id], [t1].[Value], [t1].[timestamp], [t1].[etc...]
FROM [Entity] AS [t1]
So my question is, how do I encapsulate this projection without the LINQ to SQL instantiating the whole Entity?
Things to keep in mind, the DTO I am using has a protected default constructor, so I can't use an object initializer. And since the DTO class cannot be modified, I'd have to make a subclass to implement that behavior. Which is fine, if that's the only solution.
Thanks.
Edit:
Thanks to Brian for the solution. I had previously tried an Expression but couldn't figure out the syntax. Here's the working code:
Expression<Entity, DTO> ToDTO = (e) => new DTO(e.Value);
Then call it like this:
db.Entities.Select(ToDTO);
At first I was trying to call it like this, which wouldn't compile. This is the proper syntax for calling a Func, but not an Expression.
db.Entities.Select(e => ToDTO(e));
You probably need to create an Expression, not a Func
Expression<Func<Entity, DTO>> ToDTO = (e) => new DTO(e.Value);
IQueryable extension methods work with Expressions, not Funcs
By passing in a Func, you are probably invoking the IEnumerable extension method, which is why Linq2Sql is acting the way it is.

C# LINQ problem with case sensitive

I have this:
var sortName = Request.Params["sortName"];
var query = Request.Params["query"];
Func<UsuarioEndereco, bool> whereClause = (uen => uen.GetPropValue<string>(sortName).Contains(query));
The "uen.GetPropValue<string>(sortName)" will be filled dynamically with the sortName the user typed in the page.
For example, if an user looks for a person named "Joe", the snippet will be:
(uen => uen.namePerson.Contains(Joe))
But, I'm having problems with LINQ Case-sensitive searches. If I type "Joe", I will something. On the other hand, If I type "joe", it bring nothing.
How can I make this "Contains(sortName)" works with Case-Insensitive?? I've tried some things with String.Comparer but it reports errors on build solution.
Thanks!!
I believe the following will generate proper SQL:
uen=>(uen.GetPropValue<string>(sortName)).ToLower().Contains(query.ToLower()))
If this is really LINQ-to-SQL, try using the SqlMethods.Like method instead of String.Contains.
However, I think the problem is that this is NOT LINQ-to-SQL, because you are using delegates instead of Expression trees. So this is being brought client side, then executed locally ("LINQ to Objects"). Hence, String.Contains is doing what it does locally.
In that way, James's answer is correct, since he's calling ToLower() on both the value and the query. (Although, beware of culture issues -- perhaps specify which culture you want.)
You could also use the String.IndexOf Method (String, Int32, StringComparison) (http://msdn.microsoft.com/en-us/library/ms224424.aspx). This method allows you to specify if the matching should be done case-sensitively or not, and if it should use a Invariant culture or not.
So in your example:
Func<UsuarioEndereco, bool> whereClause = (uen => uen.GetPropValue<string>(sortName).IndexOf(query, 0, StringComparison.OrdinalIgnoreCase));
I'm not commenting on if this is a better solution than the one provided by James Curran. It could or could not be, performance wise.
This is the entire code:
var sortOrder = Request.Params["sortorder"];
var sortName = Request.Params["sortname"];
var query = Request.Params["query"];
IEnumerable<UsuarioEndereco> pagedEndereco;
Func<UsuarioEndereco, bool> whereClause = (uen => uen.GetPropValue<string>(sortName).Contains(query));
pagedEndereco = sortOrder.Equals("asc", StringComparison.CurrentCultureIgnoreCase) ?
_agendaServico.SelecionaUsuarioEnderecos(u.codUsuario).Where(whereClause).OrderByDescending(uen => uen.GetPropValue<IComparable>(sortName)) :
_agendaServico.SelecionaUsuarioEnderecos(u.codUsuario).Where(whereClause).OrderBy(uen => uen.GetPropValue<IComparable>(sortName));
The Extension Method GetPropValue is:
public static T GetPropValue<T>(this object component, string propertyName)
{
return (T)TypeDescriptor.GetProperties(component)[propertyName].GetValue(component);
}