Convert a method call or assignment to a function in F# - f#

I would like to use some object-oriented code in a more functional way.
My current approach has been the following:
let addControl (child: Control) (parent: Control) =
parent.Controls.Add child
parent
let setDock dock (control : Control) =
control.Dock <- dock
control
form |> addControl button
button |> setDock DockStyle.Fill
Is there a simpler way I can define these functions?
If I take the JS approach I could define something like the following:
const fixMethod = name => value => parent => (parent[name](value), parent)
const resumeLayout = fixMethod("ResumeLayout")
resumeLayout(true)(form)
const fixAssign = name => value => parent => ({...parent, [name]: value})
const setDock = fixAssign("Dock")
setDock(DockStyle.Fill)(button)

There are various tricks you could do in F#, but none of those will make your code much nicer - I would say that most tricks you can do will actually only make it more complex and unidiomatic.
There is nothing wrong with writing some imperative-looking code if that's what the underlying libraries look like. F# does have a few features that make this easier - you can, for example, specify mutable properties directly when calling a constructor, so you can set Dock as follows:
let button = new Button(Dock = DockStyle.Fill)
let form = new Form()
form.Controls.Add(button)

Related

Chaining method calls

According to official Dart documentation, it is mentioned that:
Chaining method calls
a..b = true..c = 5;
Cascade used for chaining access to methods and other members.
Equivalent:
a.b = true; a.c = 5;
Can someone explain the meaning of the above lines?
Consider user as an instace of following class:
class User {
int age;
String firstName;
String lastName;
}
Now you can update data in user as following:
user.age = 5;
user.firstName = 'John';
user.lastName = 'Doe';
but if you use chaining access as described in the documentation.
Then it will look something like this:
user..age = 5
..firstName = 'John'
..lastName = 'Doe';
Note: sequence of assignment of the properties does not matter, but it might be of importance while calling functions or methods like this.
Just a simple & random example:
painter..computeLayout()
..initializePaint()
..render();
above is same as:
painter.computeLayout();
painter.initializePaint();
painter.render();
in the above example all of the methods were called on painter object/instance but the sequence here must be followed as without paint or layout the render will not work.
Cascades
To perform a sequence of operations on the same object, use cascades (..). We’ve all seen an expression like this:
myObject.someMethod()
It invokes someMethod() on myObject, and the result of the expression is the return value of someMethod().
Here’s the same expression with a cascade:
myObject..someMethod()
Although it still invokes someMethod() on myObject, the result of the expression isn’t the return value — it’s a reference to myObject! Using cascades, you can chain together operations that would otherwise require separate statements. For example, consider this code:
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
With cascades, the code becomes much shorter, and you don’t need the button variable:
querySelector('#confirm')
..text = 'Confirm'
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));

Is it possible to make a TreeMap from a Map literal?

I have a Map literal, an I want it to be a TreeMap, but by default I believe it's a LinkedHashMap. Casting a LinkedHashMap to a TreeMap won't work as it's not a subtype.
Basically, I'm looking for the simplest way to make this work:
var map = <int, int>{for(int i = 0; i < intervals.length; i++) intervals[i][0] : i} as SplayTreeMap;
As mentioned before, casting as SplayTreeMap won't work as they types don't align.
Thanks much in advance
Use the SplayTreeMap.from constructor to create a SplayTreeMap. There isn't any way to cast it as you said.
Remove the as from your current code and add this to get your SplayTreeMap:
var newMap = SplayTreeMap.from(map);
Depending on your key type and your use case, you can pass compare and isValidKey parameters as well. Full constructor definition:
SplayTreeMap<K, V>.from(
Map other,
[int compare(
K key1,
K key2
),
bool isValidKey(
dynamic potentialKey
)]
)

How would I use Automapper in this query?

Given
Dim postviewmodel As IEnumerable(Of be_PostsViewModel)
postviewmodel = _postRepository.SelectAll.Select(Function(S) New
be_PostsViewModel With {.PostIsPublished = S.PostIsPublished, .Id =
S.PostId, .PostSummary = S.PostSummary, .PostDateCreated =
S.PostDateCreated,
.PostCategory = S.PostCategory, .PostTitle =
S.PostTitle}).Where(Function(p)
p.PostIsPublished = True).Where(Function(a) Not
a.PostCategory.FirstOrDefault.CategoryName = "Lead Story")
.Skip((Page - 1) * PageSize).Take(PageSize)
How would I use Automapper so I don't do all thmapping of properties by hand? I am completely new to it and have been doing a lot of reading but don't quite understand how to actually do it. I know I have to create the map and then call Mapper.map. But what goes where in Mapper.map?
I would do this:
Mapper.CreateMap<Post, be_postsViewModel>();
Do that in your application startup (App_Start etc). Then in your code above:
postViewModel = _postRepository.SelectAll.Project.To(Of be_PostsViewModel)
However, I'd put the "Project.To" AFTER all of your Where/Skip/Take pieces. The projection is the last thing you want to do. Project.To creates that exact Select expression, passes it to the query provider to modify the SQL at its base.
Unless SelectAll doesn't return IQueryable, then you have other, larger problems.

Seek overview of the '=>' operator

I'm browsing sample asp.net code in an MVC project and need a better understanding of the => operator. Plugging => into search engines is non-helpful.
thx
The => syntax creates lambda expressions, which are small functions.
For example, the line
Func<int, int> myFunc = i => 2 * i;
declares a variable of type Func<int, int> (a delegate that takes one integer and returns another one), and assigns it to a lambda expressions that takes a parameter called i (the compiler automatically figures out that i is an int) and returns 2 * i.
Yo can search it as lambda. See here http://msdn.microsoft.com/en-us/library/bb397687.aspx
The => operator, as has been mentioned, represents a lambda expression. This is short-hand for an anonymous delegate. Here is practical example:
If you want to filter all Person objects in a collection to return only Male people, the Where() extension method requires a Func delegate you could create a named delegate like this:
Func<Person, bool> isMale = delegate(Person peep) { return peep.Gender == "male"; };
var men = from p in peeps.Where(isMale)
select p;
Or you could use an anonymous delegate like this:
var women = from p in peeps.Where(delegate(Person peep) { return peep.Gender != "male"; })
select p;
The lambda allows you to declare the anonymous delegate using a short-hand, like this:
var women = from p in peeps.Where(x => x.Gender != "male")
select p;
Notice the correspondence between delegate(Person peep) and x, and between 'return peep.Gender != "male"and 'x.Gender != "male".

Modeling database records as types

I'm rewriting a C# library in F# in which most of the classes map one-to-one with database tables (similar to ActiveRecord). I'm considering whether to use records or classes (maybe even DUs?). There's a fair amount of validation in the property setters to maintain invariants. What would be the best way to model this in F#? I don't want an object that violates business logic to be persisted to the database. Any ideas are welcome.
A few additional thoughts...
Is it better to move the invariants to an external 'controller' class? Coming from C# it feels wrong to allow an object that corresponds to a database record to contain anything that can't be saved to the database. I suppose because failing earlier seems better than failing later.
You can have your data in a record, and still keep the validation logic with the data type, by attaching methods to the record:
type Person =
{ First : string;
Last : string; } with
member x.IsValid () =
let hasValue = System.String.IsNullOrEmpty >> not
hasValue x.First && hasValue x.Last
let jeff = { First = "Jeff"; Last = "Goldblum" }
let jerry = { jeff with First = "Jerry" }
let broken = { jerry with Last = "" }
let valid = [jeff; jerry; broken]
|> List.filter (fun x -> x.IsValid())
The copy semantics for records are almost as convenient as setting a property. The validation doesn't happen on property set, but it's easy to filter a list of records down to only the valid ones.
This should actually be a good way for you to handle it. Having your validation logic in the constructor will give you piece of mind later on in your code because the object is immutable. This also opens up multi-threading possibilities.
Immutable Version
type Customer (id, name) =
do // Constructor
if id <= 0 then
raise(new ArgumentException("Invalid ID.", "id"))
elif String.IsNullOrEmpty(name) then
raise(new ArgumentException("Invalid Name.", "name"))
member this.ID
with get() = id
member this.Name
with get() = name
member this.ModifyName value =
new Customer(id, value)
Mutable Version
type Customer (id) =
let mutable name = ""
do // Constructor
if id <= 0 then
raise(new ArgumentException("Invalid ID.", "id"))
member this.ID
with get() = id
member this.Name
with get() = name
and set value =
if String.IsNullOrEmpty(name) then
raise(new ArgumentException("Invalid Name.", "value"))
name <- value
Have you taken a look at my FunctionalNHibernate project? It's designed as a layer on top of nhibernate to let you declaratively map records to a database. It's early days, but it's just about usable:
http://bitbucket.org/robertpi/functionalnhibernate/

Resources