Can a method from a Generic class return a Tuple with the same types as its argument-list? - ceylon

I wanted to have something like this:
[String, Integer] values = SomeClass("Hi", 1).values();
[Boolean, Float] others = SomeClass(true, 2.0).values();
// EDIT - should return tuple with same type as the arguments list
[String] strs = SomeClass("Strings").values();
Is this possible with Ceylon generics?
I suspect something similar to this should be possible after reading about currying in Ceylon, but I can't figure this out right now!!

class SomeClass<Args>(Args args)
given Args satisfies Tuple<Anything, Anything, Anything[]> {
shared Args values() => args;
}
[String, Integer] foo = SomeClass(["Hi", 1]).values();
[Boolean, Float] bar = SomeClass([true, 2.0]).values();
[String] baz = SomeClass(["Strings"]).values();

Related

F#: Apply a value as though it is a function

Is it possible in F# to apply a value as though it is a function? For example:
let record =
{|
Func = fun x -> x * x
Message = "hello"
|}
let message = record.Message // unsweetened field access
let unsweet = record.Func 3 // unsweetened function application
let sweet = record 3 // sweetened function application
Right now, the last line doesn't compile, of course:
error FS0003: This value is not a function and cannot be applied.
Is there some sort of syntactical sweetener that would allow me to "route" function application as I see fit, while still retaining its normal unsweetened behavior as well? I'm thinking of something magic like this:
// magically apply a record as though it was a function
let () record arg =
record.Func arg
(Note: I used a record in this example, but I'd be happy with a class as well.)
The closest thing I can think of would be a custom operator using statically resolved type parameters to resolve a specific property of type FSharpFunc, then invoke the function with the supplied input parameter. Something like this:
let record =
{|
Func = fun x -> x * x
Message = "hello"
|}
let inline (>.>) (r: ^a) v =
let f = (^a : (member Func: FSharpFunc< ^b, ^c>) r)
f v
record >.> 3 // val it : int = 9

EitherT with Reader generalizing over Reader input

A standard construct in my code is a function that returns a Reader[X,\/[A,B]] and I would like to use the Either portion in a for comprehension, so I have been trying to write a function which will convert a function (X) => \/[A,B] into EitherT[Reader[X,\/[A,B]],A,B].
I can do this with a predetermined Type for X. For instance:
case class Config(host: String)
type ReaderConfig[C] = Reader[Config, C]
type EitherReaderConfig[A,B] = EitherT[ReaderConfig, A,B]
def eitherReaderF[A,B](f: Config => \/[A,B]) : EitherReaderConfig[A,B] = EitherT[ReaderConfig, A,B](Reader[Config, \/[A,B]](f))
eitherReaderF(c => \/-(c.host)).run(Config("hostname"))
However, I am having problems removing the Config type and generalizing over X. This is because EitherT's first argument is expecting one argument in it's type construct: F[_], however Reader is defined as containing 2: Reader[A,B]
One of my attempts is to define a type in terms of an EitherT using type lambdas.
type EitherReaderM[X,A,B] = EitherT[({type λ[α] = Reader[X, α]})#λ, A,B]
def eitherReaderM[X,A,B](f: X => \/[A,B]): EitherReaderM[X,A,B] = EitherT[({type λ[α] = Reader[X, α]})#λ, A,B](Reader(f))
val r: EitherReaderM[Config, Int, String] = eitherReaderM((c: Config) => \/-(c.host))
val run = r.run /// type returns scalaz.Kleisli[[+X]X,Config,scalaz.\/[Int,String]]
run.apply(Config("host")) // fails: value apply is not a member of scalaz.Kleisli[[+X]X,Config,scalaz.\/[Int,String]]
That last bit fails. I feel like I'm close here.....
I'm not entirely sure what's going on yet, but I can run this with 2 calls to run. One on the EitherT and then one on the Kleisli (which I'm not sure where it came in ).
run.run(Config("host"))
However, even though this runs in the console, it doesn't actually compile. I receive this error while compiling:
kinds of the type arguments ([α]scalaz.Kleisli[[+X]X,X,α],A,B)
do not conform to the expected kinds of the type parameters (type F,type A,type B).
[α]scalaz.Kleisli[[+X]X,X,α]'s type parameters do not match type F's expected parameters:
type α is invariant, but type _ is declared covariant
[ERROR] def eitherReaderM[X,A,B](f: X => /[A,B]): EitherReaderM[X,A,B] = EitherT({type λ[α] = Reader[X, α]})#λ, A,B
And here we have it, the final, compiling version. I feel like it can be simplified a little more, but that is for a different day.
type EitherReader[X,A,B] = EitherT[({type λ[+α] = Reader[X, α]})#λ, A,B]
def eitherReader[X,A,B](f: X => \/[A,B]): EitherReader[X,A,B] = EitherT[({type λ[+α] = Reader[X, α]})#λ, A,B](Reader(f))
The allows me to replace Reader[X, A / B].apply with eitherReader[X,A,B].
Old:
def getSub(id: Int) = Reader[Config, String \/ Sub](config => config.findSub(id).right)
New:
def getSub(id: Int) = eitherReader[Config, String, Sub]](config => config.findSub(id).right)
Seems weird that I'm doing this simply for type conversion. Probably means I'm overlooking something.

What does this '()' notation mean?

I just started to learn F#. The book uses the following notation:
let name() = 3
name()
what that differs from this:
let name = 3
name
?
Before answering what () is lets get some basics defined and some examples done.
In F# a let statement has a name, zero or more arguments, and an expression.
To keep this simple we will go with:
If there are no arguments then the let statement is a value.
If there are arguments then the let statement is a function.
For a value, the result of the expression is evaluated only once and bound to the identifier; it is immutable.
For a function, the expression is evaluated each time the function is called.
So this value
let a = System.DateTime.Now;;
will always have the time when it is first evaluated or later invoked, i.e.
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
and this function
let b () = System.DateTime.Now;;
will always have a new time each time it is evaluated, i.e.
b ();;
val it : System.DateTime = 1/10/2017 8:18:41 AM ...
b ();;
val it : System.DateTime = 1/10/2017 8:18:49 AM ...
b ();;
val it : System.DateTime = 1/10/2017 8:20:32 AM ...
Now to explain what () means. Notice that System.DateTime.Now needs no arguments to work.
How do we create a function when the expression needs no arguments?
Every argument has to have a type, so F# has the unit type for functions that need no arguments and the only value for the unit type is ().
So this is a function with one argument x of type int
let c x = x + 1;;
and this is a function with one argument () of type unit
let b () = System.DateTime.Now;;
Definitely do NOT think of () as some syntax for a function call or anything like that. It's just a value, like 3, 5, 'q', false, or "blah". It happens to be a value of type Unit, and in fact it's the only value of type unit, but really that's beside the point. () here is just a value. I can't stress that enough.
First consider
let name x = 3
What's this? This just defines a function on x, where x can be any type. In C# that would be:
int Name<T>(T x)
{
return 3;
}
Now if we look at let name () = 3 (and I somewhat recommend putting that extra space there, so it makes () look more a value than some syntactic structure) then in C# you can think of it as something like (pseudocode)
int Name<T>(T x) where T == Unit //since "()" is the only possible value of Unit
{
return 3;
}
or, more simply
int Name(Unit x)
{
return 3;
}
So we see that all let name () = 3 is, the definition of a function that takes a Unit argument, and returns 3, just like the C# version above.
However if we look at let name = 3 then that's just a variable definition, just like var name = 3 in C#.
In
let name() = 3
name()
name is a function, of type unit -> int.
In
let name = 3
name
name is an integer, of type int.
In F#, every function has an input type and an output type. The input type of let name() = 3 is unit, which has only one value (). Its output type is int, which has values from –2,147,483,648 to 2,147,483,647. As another example type bool has only two values, true and false.
So back to you question what's the usage of (). If you don't specify the input value of a function, it cannot get executed. So you have to specify an input value to your function let name()=3 to get it executed and because of its input type is unit, the only value you can use is ().
Here is another way to define the name function:
let name : (unit -> int) = (fun _ -> 3);;
and compare this to:
let name : int = 3
Using () creates a function which takes a paramter of type unit, rather than the second case which is just a simple integer.
This is particularly important when you want to control execution of the function.
The main difference is when you have
let name() =
printfn "hello"
1
vs
let name =
printfn "hello"
1
then
let t = name + name
will print "hello" once. But
let t = (name()) + (name())
will print "hello" twice.
You have to be careful with this when considering the order in which functions are evaluated.
Consider the following program:
let intversion =
printfn "creating integer constant"
1
printfn "integer created"
let funcversion() =
printfn "executing function"
1
printfn "function created"
let a = intversion + intversion
printfn "integer calculation done"
let b = (funcversion()) + (funcveriosn())
printfn "function calculation done"
This will print the following in order
creating integer constant
integer created
function created
integer calculation done
executing function
executing function
function calculation done

How do I make lambda functions generic in Scala? [duplicate]

This question already has answers here:
How can I define an anonymous generic Scala function?
(2 answers)
Closed 9 years ago.
As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method...
making the 'def' kind generic is fairly straight forward
def someFunc[T](a: T) { // insert body here
what I'm having trouble with here is how to make the following generic:
val someFunc = (a: Int) => // insert body here
of course right now a is an integer, but what would I need to do to make it generic?
val someFunc[T] = (a: T) => doesn't work, neither does val someFunc = [T](a: T) =>
Is it even possible to make them generic, or should I just stick to the 'def' variant?
As Randall Schulz said, def does not create a function, but a method. However, it can return a function and this way you can create generic functions like the identity function in Predef. This would look like this:
def myId[A] = (a: A) => a
List(1,2,3) map myId
// List(1,2,3)
List("foo") map myId
// List("foo")
But be aware, that calling myId without any type information infers Nothing. In the above case it works, because the type inference uses the signature of map, which is map[B](f: A => B) , where A is the type of the list and B gets infered to the same as A, because that is the signature of myId.
I don't believe it's possible. You can look at this previous post for more details:
How can I define an anonymous generic Scala function?
The only way around it (as one of the answers mentions) is to extend something like FunctionX and use a generic at the class level and then use that in the override of the apply function.
I don't believe it's possible either, but I'm a pessimist.
http://www.chuusai.com/2012/04/27/shapeless-polymorphic-function-values-1/
Edit:
Tell me if this isn't what you're asking, but this is why the accepted answer isn't what I thought you were asking for, see the link:
scala> :pa
// Entering paste mode (ctrl-D to finish)
def myId[A] = (a: A) => a
List(1,2,3) map myId
// List(1,2,3)
List("foo") map myId
// List("foo")
// Exiting paste mode, now interpreting.
myId: [A]=> A => A
res0: List[String] = List(foo)
scala> val f1 = myId[Int]
f1: Int => Int = <function1>
scala> val f2 = myId[String]
f2: String => String = <function1>
scala> List(1,2,3) map f2
<console>:10: error: type mismatch;
found : String => String
required: Int => ?
List(1,2,3) map f2
^
scala> List("foo") map f1
<console>:10: error: type mismatch;
found : Int => Int
required: String => ?
List("foo") map f1
^
The function values are not polymorphic, i.e., generic.
The closest thing is polymorphic functions I believe:
https://github.com/milessabin/shapeless#polymorphic-function-values

Passing functions and operating on their results within Scala's Actors

I'm implementing an actor-based app in scala and I'm trying to be able to pass functions between the actors for them to be processed only when some message is received by the actor.
import actors.Actor
import java.util.Random
import scala.Numeric._
import Implicits._
class Constant(val n:Number) extends Actor{
def act(){
loop{
receive{
case "value" => reply( {n} )
}
}
}
}
class Arithmetic[T: Numeric](A: ()=>T, B: ()=>T) extends Actor{
def act(){
receive{
case "sum" => reply ( A() + B() )
/* case "mul" => reply ( A * B )
*/
}
}
}
object Main extends App{
val c5 = new Constant(5)
c5.start
val a = new Arithmetic({c5 !! "value"}, {c5!!"value"} )
a.start
println(a!?"sum")
println(a!?"mul")
}
In the example code above I would expect the output to be both 5+5 and 5*5. The issue is that reply is not a typed function and as such I'm unable to have the operator (+,*) to operate over the result from A and B.
Can you provide any help on how to better design/implement such system?
Edit: Code updated to better reflect the problem. Error in:
error: could not find implicit value for evidence parameter of type Numeric[Any]
val a = new Arithmetic({c5 !! "value"}, {c5!!"value"} )
I need to be able to pass the function to be evaluated in the actor whenever I call it. This example uses static values but I'll bu using dynamic values in the future, so, passing the value won't solve the problem. Also, I would like to receive different var types (Int/Long/Double) and still be able to use the same code.
The error: Error in: error: could not find implicit value for evidence parameter of type Numeric[Any]. The definition of !!:
def !! (msg: Any): Future[Any]
So the T that Arithmetic is getting is Any. There truly isn't a Numeric[Any].
I'm pretty sure that is not your problem. First, A and B are functions, and functions don't have + or *. If you called A() and B(), then you might stand a chance... except for the fact that they are java.lang.Number, which also does not have + or * (or any other method you'd expect it to have).
Basically, there's no "Number" type that is a superclass or interface of all numbers for the simple reason that Java doesn't have it. There's a lot of questions touching this subject on Stack Overflow, including some of my own very first questions about Scala -- investigate scala.math.Numeric, which is the best approximation for the moment.
Method vs Function and lack of parenthesis
Methods and functions are different things -- see tons of related questions here, and the rule regarding dropping parenthesis is different as well. I'll let REPL speak for me:
scala> def f: () => Int = () => 5
f: () => Int
scala> def g(): Int = 5
g: ()Int
scala> f
res2: () => Int = <function0>
scala> f()
res3: Int = 5
scala> g
res4: Int = 5
scala> g()
res5: Int = 5