How to declare a block argument with one or two arguments in crystal - proc

I want to be able accept a block argument, which takes one or two Int arguments
This code does not work, but expresses my intent.
def initialize(*input, &block : (Int32 | (Int32, Int32)) -> Int32)
#input = input
#calc = block
end
This works for a block with one Int argument. How do I make it work with one or two Int arguments?

Taking a block parameter is optional in Crystal. So just declare the the block with the maximum number of arguments and decide on the call side how many of those you're going to take:
def foo(&block : (Int32, Int32) -> Int32)
block.call(1, 2)
end
foo {|a, b| a + b } # => 3
foo {|a| a } # => 1
foo { 5 } # => 5

Related

Lua: colon and dot function invocation acting differently

I initially came across this while developing my game in LOVE2D, and I can't figure out why.
As much as I know, x:foo() is just a syntactic sugar for x.foo(self) but combining this with other classes results in some weird behavior.
Basically, I have two programs
y = {}
function y:bar()
return self.b
end
x = {}
function x:foo()
return y.bar(self)
end
print(x.foo({b = 3}))
This prints 3 as expected
y = {}
function y:bar()
return self.b
end
x = {}
function x:foo()
return y:bar()
end
print(x.foo({b = 3}))
But this prints nil !!
I don't understand, why are these two programs printing different things?
x:foo() is syntactic sugar for x.foo(x)
which means that
function x:foo()
return y:bar()
end
is actually
function x:foo()
return y.bar(y)
end
look again at your use of self
function x:foo()
return y.bar(self) -- = y.bar(x)
end
function x:foo()
return y:bar() -- = y.bar(y)
end
x:foo() is just a syntactic sugar for x.foo(self)
This is correct in the context of a function definition but not as an expression.
function x.y.z:foo(a, b)
print(self, a, b)
end
is the same as
function x.y.z.foo(self, a, b)
print(self, a, b)
end
A function definition being set into a table field can be a method, that is with a :. Nested table fields are also allowed, for methods and non-methods, if the keys are strings that are valid Lua identifiers, as in x.y.z.
But
print(x.y().z:foo(a, b))
is the same as
local _ = x.y().z
print(_.foo(_, a, b))
With the method call syntax, the lefthand-side of : is an expression (x.y().z) that is evaluated only once.

How to implement variable arguments in F#

I want to implement a F# function which may accept 1 or 2 arguments. I would like to use the function like this:
let foo = ...
foo "a"
foo "a" "b"
Both the arguments can be the same type. I read the pages about match pattern, active pattern, but cannot find one works for me.
I believe this is due to some of the underlying .Net features, but I think you have to use a class with overloaded methods - something like
type t() =
static member foo a = "one arg"
static member foo (a,b) = "two args"
On a type member, you can use optional params:
type Helper private () =
static member foo (input1, ?input2) =
let input2 = defaultArg input2 "b"
input1, input2
To call this method:
Helper.foo("a")
Helper.foo("a", "b")
Is this what you're after?
You can't use optional params on a function though, unfortunately.
In addition to the other answers, here are a few more "almost solutions". They are not strictly what you wanted, but are worth knowing anyway.
Using a list (or an array) and pattern matching:
let f = function
| [a, b] -> ...
| [a] -> ...
| [] -> failwith "too few arguments"
| _ -> failwith "too many arguments"
f ["a"]
f ["a" ; "b"]
Problems: parameters are not named, not clear from function signature how many parameters it takes.
Using a record to pass all optional parameters:
type FParams = { a : string; b : string }
let fdefault = { a = "a" ; b = "b" }
let f (pars: FParams) = ...
f { fdefault with b = "c" }
Problem: a is also optional, which is not what you wanted. Can be useful though.
In addition to the other answers, you might also be able to do what you want via partial application and currying. Like this:
let foo a b =
a + b
let foo2 a =
foo 1 a;;
Obviously you'd want to fix the first parameter in the call to foo within foo2 to whatever default you want.

Scala read-eval-print using RegexParser without so much boilerplate?

I'm implementing part of a Scala program that takes input strings of the form "functionName arg1=x1 arg2=x2 ...", parses the xi to the correct types, and then calls a corresponding Scala function functionName(x1,x2,...). The code below is an example implementation with two functions foo and bar, which take different kinds of arguments.
Notice that the types and argument names of foo and bar have to be handwritten into the code in several places: the original function definitions, defining the case classes that the parser returns, and the parsers themselves. The case classes returned by the parser also do basically nothing interesting -- I'm tempted to just call foo and bar from within the parser, but I feel like that would be icky.
My question is: can this implementation be simplified? In practice, I will have many functions with complicated argument types, and I'd prefer to be able to specify those types as few times as possible, and perhaps also not have to define corresponding case classes.
type Word = String
// the original function definitions
def foo(x: Int, w: Word) = println("foo called with " + x + " and " + w)
def bar(y: Int, z: Int) = println("bar called with " + y + " and " + z)
// the return type for the parser
abstract class Functions
case class Foo(x: Int, w: Word) extends Functions
case class Bar(y: Int, z: Int) extends Functions
object FunctionParse extends RegexParsers {
val int = """-?\d+""".r ^^ (_.toInt)
val word = """[a-zA-Z]\w*""".r
val foo = "foo" ~> ("x=" ~> int) ~ ("w=" ~> word) ^^ { case x~w => Foo(x,w) }
val bar = "bar" ~> ("y=" ~> int) ~ ("z=" ~> int) ^^ { case y~z => Bar(y,z) }
val function = foo | bar
def parseString(s: String) = parse(function, s)
}
def main(args: Array[String]) = {
FunctionParse.parseString(args.mkString(" ")) match {
case FunctionParse.Success(result, _) => result match {
case Foo(x, w) => foo(x, w)
case Bar(y, z) => bar(y, z)
}
case _ => println("sux.")
}
}
Edit: I should note that in my case, the specific format above for the input string is not very important -- I'm happy to change it (use xml or whatever) if it results in cleaner, simpler Scala code.
You want reflection, to put it simply. Reflection means finding out, instantiating and calling classes and methods at runtime instead of compile time. For example:
scala> val clazz = Class forName "Foo"
clazz: Class[_] = class Foo
scala> val constructors = clazz.getConstructors
constructors: Array[java.lang.reflect.Constructor[_]] = Array(public Foo(int,java.lang.String))
scala> val constructor = constructors(0)
constructor: java.lang.reflect.Constructor[_] = public Foo(int,java.lang.String)
scala> constructor.getParameter
getParameterAnnotations getParameterTypes
scala> val parameterTypes = constructor.getParameterTypes
parameterTypes: Array[Class[_]] = Array(int, class java.lang.String)
scala> constructor.newInstance(5: Integer, "abc")
res6: Any = Foo(5,abc)
This is all Java reflection. Scala 2.9 still doesn't have a Scala-specific reflection interface, though one is already in development and might well be available on the next version of Scala.
What you're doing looks very reasonable. The only way to 'simplify' it in my mind would be to have less explicit types and/or use reflection to look up the appropriate function...
Update: Daniel's answer is a good example of how to use reflection. In terms of less explicit types, you would have to have the function arguments to be Any...

"int -> int -> int" What does this mean in F#?

I wonder what this means in F#.
“a function taking an integer, which returns a function which takes an integer and returns an integer.”
But I don't understand this well.
Can anyone explain this so clear ?
[Update]:
> let f1 x y = x+y ;;
val f1 : int -> int -> int
What this mean ?
F# types
Let's begin from the beginning.
F# uses the colon (:) notation to indicate types of things. Let's say you define a value of type int:
let myNumber = 5
F# Interactive will understand that myNumber is an integer, and will tell you this by:
myNumber : int
which is read as
myNumber is of type int
F# functional types
So far so good. Let's introduce something else, functional types. A functional type is simply the type of a function. F# uses -> to denote a functional type. This arrow symbolizes that what is written on its left-hand side is transformed into what is written into its right-hand side.
Let's consider a simple function, that takes one argument and transforms it into one output. An example of such a function would be:
isEven : int -> bool
This introduces the name of the function (on the left of the :), and its type. This line can be read in English as:
isEven is of type function that transforms an int into a bool.
Note that to correctly interpret what is being said, you should make a short pause just after the part "is of type", and then read the rest of the sentence at once, without pausing.
In F# functions are values
In F#, functions are (almost) no more special than ordinary types. They are things that you can pass around to functions, return from functions, just like bools, ints or strings.
So if you have:
myNumber : int
isEven : int -> bool
You should consider int and int -> bool as two entities of the same kind: types. Here, myNumber is a value of type int, and isEven is a value of type int -> bool (this is what I'm trying to symbolize when I talk about the short pause above).
Function application
Values of types that contain -> happens to be also called functions, and have special powers: you can apply a function to a value. So, for example,
isEven myNumber
means that you are applying the function called isEven to the value myNumber. As you can expect by inspecting the type of isEven, it will return a boolean value. If you have correctly implemented isEven, it would obviously return false.
A function that returns a value of a functional type
Let's define a generic function to determine is an integer is multiple of some other integer. We can imagine that our function's type will be (the parenthesis are here to help you understand, they might or might not be present, they have a special meaning):
isMultipleOf : int -> (int -> bool)
As you can guess, this is read as:
isMultipleOf is of type (PAUSE) function that transforms an int into (PAUSE) function that transforms an int into a bool.
(here the (PAUSE) denote the pauses when reading out loud).
We will define this function later. Before that, let's see how we can use it:
let isEven = isMultipleOf 2
F# interactive would answer:
isEven : int -> bool
which is read as
isEven is of type int -> bool
Here, isEven has type int -> bool, since we have just given the value 2 (int) to isMultipleOf, which, as we have already seen, transforms an int into an int -> bool.
We can view this function isMultipleOf as a sort of function creator.
Definition of isMultipleOf
So now let's define this mystical function-creating function.
let isMultipleOf n x =
(x % n) = 0
Easy, huh?
If you type this into F# Interactive, it will answer:
isMultipleOf : int -> int -> bool
Where are the parenthesis?
Note that there are no parenthesis. This is not particularly important for you now. Just remember that the arrows are right associative. That is, if you have
a -> b -> c
you should interpret it as
a -> (b -> c)
The right in right associative means that you should interpret as if there were parenthesis around the rightmost operator. So:
a -> b -> c -> d
should be interpreted as
a -> (b -> (c -> d))
Usages of isMultipleOf
So, as you have seen, we can use isMultipleOf to create new functions:
let isEven = isMultipleOf 2
let isOdd = not << isEven
let isMultipleOfThree = isMultipleOf 3
let endsWithZero = isMultipleOf 10
F# Interactive would respond:
isEven : int -> bool
isOdd : int -> bool
isMultipleOfThree : int -> bool
endsWithZero : int -> bool
But you can use it differently. If you don't want to (or need to) create a new function, you can use it as follows:
isMultipleOf 10 150
This would return true, as 150 is multiple of 10. This is exactly the same as create the function endsWithZero and then applying it to the value 150.
Actually, function application is left associative, which means that the line above should be interpreted as:
(isMultipleOf 10) 150
That is, you put the parenthesis around the leftmost function application.
Now, if you can understand all this, your example (which is the canonical CreateAdder) should be trivial!
Sometime ago someone asked this question which deals with exactly the same concept, but in Javascript. In my answer I give two canonical examples (CreateAdder, CreateMultiplier) inf Javascript, that are somewhat more explicit about returning functions.
I hope this helps.
The canonical example of this is probably an "adder creator" - a function which, given a number (e.g. 3) returns another function which takes an integer and adds the first number to it.
So, for example, in pseudo-code
x = CreateAdder(3)
x(5) // returns 8
x(10) // returns 13
CreateAdder(20)(30) // returns 50
I'm not quite comfortable enough in F# to try to write it without checking it, but the C# would be something like:
public static Func<int, int> CreateAdder(int amountToAdd)
{
return x => x + amountToAdd;
}
Does that help?
EDIT: As Bruno noted, the example you've given in your question is exactly the example I've given C# code for, so the above pseudocode would become:
let x = f1 3
x 5 // Result: 8
x 10 // Result: 13
f1 20 30 // Result: 50
It's a function that takes an integer and returns a function that takes an integer and returns an integer.
This is functionally equivalent to a function that takes two integers and returns an integer. This way of treating functions that take multiple parameters is common in functional languages and makes it easy to partially apply a function on a value.
For example, assume there's an add function that takes two integers and adds them together:
let add x y = x + y
You have a list and you want to add 10 to each item. You'd partially apply add function to the value 10. It would bind one of the parameters to 10 and leaves the other argument unbound.
let list = [1;2;3;4]
let listPlusTen = List.map (add 10)
This trick makes composing functions very easy and makes them very reusable. As you can see, you don't need to write another function that adds 10 to the list items to pass it to map. You have just reused the add function.
You usually interpret this as a function that takes two integers and returns an integer.
You should read about currying.
a function taking an integer, which returns a function which takes an integer and returns an integer
The last part of that:
a function which takes an integer and returns an integer
should be rather simple, C# example:
public int Test(int takesAnInteger) { return 0; }
So we're left with
a function taking an integer, which returns (a function like the one above)
C# again:
public int Test(int takesAnInteger) { return 0; }
public int Test2(int takesAnInteger) { return 1; }
public Func<int,int> Test(int takesAnInteger) {
if(takesAnInteger == 0) {
return Test;
} else {
return Test2;
}
}
You may want to read
F# function types: fun with tuples and currying
In F# (and many other functional languages), there's a concept called curried functions. This is what you're seeing. Essentially, every function takes one argument and returns one value.
This seems a bit confusing at first, because you can write let add x y = x + y and it appears to add two arguments. But actually, the original add function only takes the argument x. When you apply it, it returns a function that takes one argument (y) and has the x value already filled in. When you then apply that function, it returns the desired integer.
This is shown in the type signature. Think of the arrow in a type signature as meaning "takes the thing on my left side and returns the thing on my right side". In the type int -> int -> int, this means that it takes an argument of type int — an integer — and returns a function of type int -> int — a function that takes an integer and returns an integer. You'll notice that this precisely matches the description of how curried functions work above.
Example:
let f b a = pown a b //f a b = a^b
is a function that takes an int (the exponent) and returns a function that raises its argument to that exponent, like
let sqr = f 2
or
let tothepowerofthree = f 3
so
sqr 5 = 25
tothepowerofthree 3 = 27
The concept is called Higher Order Function and quite common to functional programming.
Functions themselves are just another type of data. Hence you can write functions that return other functions. Of course you can still have a function that takes an int as parameter and returns something else. Combine the two and consider the following example (in python):
def mult_by(a):
def _mult_by(x):
return x*a
return mult_by
mult_by_3 = mult_by(3)
print mylt_by_3(3)
9
(sorry for using python, but i don't know f#)
There are already lots of answers here, but I'd like to offer another take. Sometimes explaining the same thing in lots of different ways helps you to 'grok' it.
I like to think of functions as "you give me something, and I'll give you something else back"
So a Func<int, string> says "you give me an int, and I'll give you a string".
I also find it easier to think in terms of 'later' : "When you give me an int, I'll give you a string". This is especially important when you see things like myfunc = x => y => x + y ("When you give curried an x, you get back something which when you give it a y will return x + y").
(By the way, I'm assuming you're familiar with C# here)
So we could express your int -> int -> int example as Func<int, Func<int, int>>.
Another way that I look at int -> int -> int is that you peel away each element from the left by providing an argument of the appropriate type. And when you have no more ->'s, you're out of 'laters' and you get a value.
(Just for fun), you can transform a function which takes all it's arguments in one go into one which takes them 'progressively' (the official term for applying them progressively is 'partial application'), this is called 'currying':
static void Main()
{
//define a simple add function
Func<int, int, int> add = (a, b) => a + b;
//curry so we can apply one parameter at a time
var curried = Curry(add);
//'build' an incrementer out of our add function
var inc = curried(1); // (var inc = Curry(add)(1) works here too)
Console.WriteLine(inc(5)); // returns 6
Console.ReadKey();
}
static Func<T, Func<T, T>> Curry<T>(Func<T, T, T> f)
{
return a => b => f(a, b);
}
Here is my 2 c. By default F# functions enable partial application or currying. This means when you define this:
let adder a b = a + b;;
You are defining a function that takes and integer and returns a function that takes an integer and returns an integer or int -> int -> int. Currying then allows you partiallly apply a function to create another function:
let twoadder = adder 2;;
//val it: int -> int
The above code predifined a to 2, so that whenever you call twoadder 3 it will simply add two to the argument.
The syntax where the function parameters are separated by space is equivalent to this lambda syntax:
let adder = fun a -> fun b -> a + b;;
Which is a more readable way to figure out that the two functions are actually chained.

F# block arguments

C# has anonymous delegates. So I can write:
public vois foo(string d, Action t){
t();
}
In ruby:
def foo d
yield
end
How to do the same in F#? Prefered syntax is:
foo "dfdfdf" { do something here }
Thanks
Your first example isn't an anonymous method -- it's just passing and calling through a delegate (which might refer to a named or an anonymous method). To do this in F#, just provide and call a function argument:
let foo n f = f n
let square n = n * n
let result = foo 123 square
printfn "%A" result
To create the equivalent of an anonymous method in F#, use the fun keyword:
let result2 = foo 123 (fun n -> n * n)
Have a look at this article about Higher Order Functions in F#. Higher Order Functions are functions which accept other functions as arguments, and sound like the concept you are describing.
open System
// create a function that expects an Action delegate and executes it
let foo (actionDelegate:Action) (s:String) = actionDelegate.Invoke();
// create a function that meets Action delegate
let ActionFunction param = Console.Write("Action in action")
// call foo passing ActionFunction
foo (new Action(ActionFunction)) "my string"

Resources