Lambdas, alphas in Scalaz - scalaz

In many traits' signatures one can spot this awkwardly looking syntax:
private trait CompositionPlus[F[_], G[_]] extends Plus[λ[α => F[G[α]]]]
Could somebody explain to me the λ[α => F[G[α]]] part? Both λ and α seems undefined.
EDIT:
I see what this syntax does but I wonder how is it interpreted by the compiler.

This syntax comes from kind-projector. It is a compiler plugin that rewrites
λ[α => F[G[α]]]
to
({ type L[α] = F[G[α]] })#L

Related

def or val for defining Function in Scala

I'm learning Programming Paradigms in my University and reading this course material provided by the lecturer that defined a function this way:
val double = (x: Int) => 2 * x
double: Int => Int = <function1>
But from my own studies I found and got used to defining the same function like this:
def d (x: Int) = 2 * x
d: (x: Int)Int
I'm new to Scala. And both definitions give a result of:
res21: Int = 8
Upon passing 4 as the parameter.
Now my main question is why would the lecturer prefer to use val to define a function? I see it as longer and not really necessary unless using val gives some added advantages that I don't know of. Besides I understand using val makes some name a placeholder so later in the program, I could mistakenly write val double = 5 and the function would be gone!
At this stage I'm quite convinced I learned a better way of defining a function unless someone would tell me otherwise.
Strictly speaking def d (x: Int) = 2 * x is a method, not a Function, however scala can transparently convert (lift) methods into Functions for us. So that means you can use the d method anywhere that requires a Int => Int Function.
There is a small overhead of performing this conversion, as a new Function instance is created every time. We can see this happening here:
val double = (x: Int) => 2 * x
def d (x: Int) = 2 * x
def printFunc(f: Int => Int) = println(f.hashCode())
printFunc(double)
printFunc(double)
printFunc(d)
printFunc(d)
Which results in output like so:
1477986427
1477986427
574533740
1102091268
You can see when explicitly defining a Function using a val, our program only creates a single Function and reuses it when we pass as an argument to printFunc (we see the same hash code). When we use a def, the conversion to a Function happens every time we pass it to printFunc and we create several instances of the Function with different hash codes. Try it
That said, the performance overhead is small and often doesn't make any real difference to our program, so defs are often used to define Functions as many people find them more concise and easier to read.
In Scala, function values are monomorphic (i.e. they can not have type parameters, aka "generics"). If you want a polymorphic function, you have to work around this, for example by defining it using a method:
def headOption[A]: List[A] => Option[A] = {
case Nil => None
case x::xs => Some(x)
}
It would not be valid syntax to write val headOption[A]. Note that this didn't make a polymorphic function value, it is just a polymorphic method, returning a monomorphic function value of the appropriate type.
Because you might have something like the following:
abstract class BaseClass {
val intToIntFunc: Int => Int
}
class A extends BaseClass {
override val intToIntFunc = (i: Int) => i * 2
}
So its purpose might not be obvious with a very simple example. But that Function value could itself be passed to higher order functions: functions that take functions as parameters. If you look in the Scala collections documentation you will see numerous methods that take functions as parameters. Its a very powerful and versatile tool, but you need to get to a certain complexity and familiarity with algorithms before the cost /benefit becomes obvious.
I would also suggest not using "double" as an identifier name. Although legal Scala, it is easy to confuse it with the type Double.

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.

Scala by Example - type bounds parametrized function compiler complains

I would like to implement a type-parametrized function as per excersize on page 72 of the book (implement forall using filter):
def forallA[B <: A](xs:List[A])(f:A => B) : List[B] = {
xs.filter(x => true) match {
case Nil => Nil
case y :: ys => f(y) :: forallA(ys)(f)
}
}
However, the compiler(2.9.1) complains about the type A being undefined. Clearly that should not be the case, since multiple examples in the same book use this syntax. The issue can be cured by changnig the function type parameter to [A, B <: A]. Am I doing something wrong, or is it again, a terrific change in Scala's syntax specification? If so, I am, frankfully, tired of bombing SO with such stupid questions on every second excersize. Could anyone recommend a book that clearly reflects the current order of things?
You already gave the answer: If you want to bound the type parameter B with another type parameter A, you have to add this to the list of type parameters:
def forall[A, B <: A](...)(...) = ...
Else you are referring to something undefined. Maybe it helps if you think of type parameters like usual (method) parameters. How should something like the following compile:
def add(x: Int) = x + y
Here the parameter y is undefined, just like in your case A was undefined.

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);
}