We got three functions. The first one defines type alias for Boolean condition
type Set = Int => Boolean
I understand that this is the alias definition. Now the second fucntion
def contains(set: Set, elem: Int): Boolean = set(elem)
calls the (Int=>Boolean) on elem:Int.
QUESTION 1: Where is the logic of the function under Set?
I mean, do I have to pass the Set function actual parameter (in which case the contains is a higher order function) when calling contains eg. for even numbers set:
val in:Boolean = contains({x=>(x%2)==0},2)
In the third function:
def singletonSet(elem: Int): Set = set => set == elem
Question 2: Where does the set come form? Its not in the formal parameter list.
QUESTION 1: Yes, you have to pass a Set which would be the "implementation" of the function. The point of this exercise (Odersky's course?) is to show that a Set can be defined not as a collection of items (the "usual" definition of a set), but rather as a function that says whether an item is included in the set or not. So the Set is the function.
QUESTION 2: set is the name given to the argument of the anonymous function we're returning here: Since singletonSet's return type is Set, which as we've said is actually a function of type Int => Boolean, we return an (anonymous) function. To create such a function, one uses the syntax x => f(x), where x is any name you'd like and f(x) is an expression using it (or not).
1) Since a Set is a function, contains is indeed a higher order function which takes a function and an element of the appropriate type and applies the function to the element. The logic of it is that sets are being represented by Boolean-valued functions where an element evaluates to true if and only if it is in the corresponding set. The function contains evaluates the function at the element and returns its value, which is either true or false depending on whether or not it is in the set.
2) singleton returns an anonymous function, one that evaluates to true if and only if the input (set) equals the element in question.
Related
I have a function called collatz and I need to find how many times it calls itself, but I'm not allowed to use any vars.
The function works perfectly with vars but i have to use vals.
In case sinanspd's answer does not answer your question, here is some example code.
Let us say your function collatz has a signature as follows:
def collatz(input: Type1): Type2 = ???
The way to count how many times it is called is to either modify collatz itself, or else to use some wrapper function.
def counter(oldCount: Int, fun: Type1 => Type2, input: Type1): (Int, Type2) = {
val output = fun(input)
(oldCount + 1, output)
}
The first time you call counter, call it with oldCount set to 0. Every time you call counter, pass in the old version of count. The first value of your output tuple will be the new count.
I have a requirement like: Call a function with 2 parameters in different situations.
function => getSum(a, b)
here it can be like,
a has value but not b then it should be like getSum(a = value goes here)
b has value but not a then it should be like getSum(b = value goes here)
a and b have values then it should be like getSum(a, b)
a and b are uuid, and a and b are treated separately in the function.
Is it possible to specify a value to the parameter?
For that you would use default values:
CREATE FUNCTION getsum(
a uuid DEFAULT '...',
b uuid DEFAULT '...'
) RETURNS ...
You can call the function like this:
SELECT getsum(b => '...');
Then the default value will be used for a.
When you have variable parameters in a macro, for instance
<#macro m a b c...>
Do you have to pass a minimum of 3 arguments or 2 while calling the macro? Does the parameter c here have to have at least 1 value? Also is there any way to specify a parameter as null by default?
<#macro name param1 param2 ... paramN>
...
<#nested loopvar1, loopvar2, ..., loopvarN>
...
<#return>
...
</#macro>
Where:
name: name of macro variable. It's not an expression. It follows the
same syntax as like top-level variable references, like myMacro or
my-macro. However, it can also be written as a string literal, which
is useful if the macro name contains characters that can't be
specified in an identifier, for example <#macro "foo~bar">.... Note
that this string literal does not expand interpolations (as
"${foo}").
param1, param2, ...etc.: the name of the local variables store the
parameter values (not expression), optionally followed by = and the
default value (that's an expression). The default value can even be
another parameter, for example <#macro section title label=title>.
The parameter name uses the same syntax as like top-level variable
references, so the same features and restrictions apply.
paramN, the last parameter may optionally has 3 trailing dots (...),
which indicates that the macro takes a variable number of parameters
and the parameters that doesn't match any other parameters will be
collected in this last parameter (also called the catch-all
parameter). When the macro is called with named parameters, paramN
will be a hash containing all of the undeclared key/value pairs
passed to the macro. When the macro is called using positional
parameters, paramN will be the sequence of the extra parameter
values. (Inside the macro, to find out which was the case, you can
use myCatchAllParam?is_sequence.)
Therefore as you can see macro does not have any limitation to take N parameters.
This structure creates a macro variable (in the current namespace, if you know namespace feature). If you are new to macros and user-defined directives you should read the the tutorial about user-defined directives.
Macro variable stores a template fragment (called macro definition body) that can be used as user-defined directive. The variable also stores the name of allowed parameters to the user-defined directive. You must give value for all of those parameters when you use the variable as directive, except for parameters that has a default value. The default value will be used if and only if you don't give value for the parameter when you call the macro.
The variable will be created at the beginning of the template; it does not mater where the macro directive is placed in the template.
Example: Macro with parameters:
<#macro test foo bar baaz>
Test text, and the params: ${foo}, ${bar}, ${baaz}
</#macro>
<#-- call the macro: -->
<#test foo="a" bar="b" baaz=5*5-2/>
Output:
Test text, and the params: a, b, 23
Example: Macro with parameters and default parameter values:
<#macro test foo bar="Bar" baaz=-1>
Test text, and the params: ${foo}, ${bar}, ${baaz}
</#macro>
<#test foo="a" bar="b" baaz=5*5-2/>
<#test foo="a" bar="b"/>
<#test foo="a" baaz=5*5-2/>
<#test foo="a"/>
Output:
Test text, and the params: a, b, 23
Test text, and the params: a, b, -1
Test text, and the params: a, Bar, 23
Test text, and the params: a, Bar, -1
However, about last part of your question there is an explanation:
The null reference is by design an error in FreeMarker. Defining a custom null value - which is a string - is not a good idea for the reasons you mention. The following constructs should be used instead:
Macro and function parameters can have a default value, so the
callers can omit them
To check if a variable is null, you should use the ?? operator: <#if
(name??)>
When you use a variable that can be null, you should use the !
operator to specify a default value: name!"No name"
To check if a sequence (or a string) is empty, use the ?has_content
builtin: <#if (names?has_content)>
You can specify an empty sequence as default parameter value in a macro, and simply test whether it's empty.
When you have variable parameters in a macro, you don't have to pass a value for the last argument.
For example:
<#macro m a b c...>
a = ${a!}
b = ${b!}
<#list c?keys as attr>
${attr} = ${c[attr]}
</#list>
</#macro>
<#m a='A' b='B' />
<#m a='A' b='B' c='C' d='D'/>
Will output:
a = A
b = B
a = A
b = B
c = C
d = D
I am trying to build a list in scala that given input (length,and a function) the output would be a list from 0 up to that length-1.
for example:
listMaker(3,f) = List(0,1,2)
so far I have created a helper class that takes 2 int and returns a list in that range.
the listMaker function is as follows:
def listMaker[A](length:Int, f:Int =>A):List[A] = length match{
case 0 => List()
case _ => listMaker(length,f)
}
my f function just takes a variable x and returns that:
def f(x:Int)=x
the comment below makes sense, but it still gets me errors. I think the edited code is an easier way to get where I would like to
However, now I get an infinite loop. What part of the logic am I missing?
A recursive function typically has to gradually "bite off" pieces of the input data until there is nothing left - otherwise it can never terminate.
What this means in your particular case is that length must decrease on each recursive call until it reaches zero.
def listMaker[A](length:Int, f:Int =>A):List[A] = length match{
case 0 => List()
case _ => listMaker(length,f)
}
But you are not reducing length - you are passing it unchanged to the next recursive call, so, your function cannot terminate.
(There are other problems too - you need to build up your result list as you recurse, but your current code simply returns an empty list. I assume this is a learning exercise, so I'm not supplying working code...).
I'm trying to write a DAC macro that gets as input the name of list of bits and its size, and the name of integer variable. Every element in the list should be constrained to be equal to every bit in the variable (both of the same length), i.e. (for list name list_of_bits and variable name foo and their length is 4) the macro's output should be:
keep list_of_bits[0] == foo[0:0];
keep list_of_bits[1] == foo[1:1];
keep list_of_bits[2] == foo[2:2];
keep list_of_bits[3] == foo[3:3];
My macro's code is:
define <keep_all_bits'exp> "keep_all_bits <list_size'exp> <num'name> <list_name'name>" as computed {
for i from 0 to (<list_size'exp> - 1) do {
result = appendf("%s keep %s[%d] == %s[%d:%d];",result, <list_name'name>, index, <num'name>, index, index);
};
};
The error I get:
*** Error: The type of '<list_size'exp>' is 'string', while expecting a
numeric type
...
for i from 0 to (<list_size'exp> - 1) do {
Why it interprets the <list_size'exp> as string?
Thank you for your help
All macro arguments in DAC macros are considered strings (except repetitions, which are considered lists of strings).
The point is that a macro treats its input purely syntactically, and it has no semantic information about the arguments. For example, in case of an expression (<exp>) the macro is unable to actually evaluate the expression and compute its value at compilation time, or even to figure out its type. This information is figured out at later compilation phases.
In your case, I would assume that the size is always a constant. So, first of all, you can use <num> instead of <exp> for that macro argument, and use as_a() to convert it to the actual number. The difference between <exp> and <num> is that <num> allows only constant numbers and not any expressions; but it's still treated as a string inside the macro.
Another important point: your macro itself should be a <struct_member> macro rather than an <exp> macro, because this construct itself is a struct member (namely, a constraint) and not an expression.
And one more thing: to ensure that the list size will be exactly as needed, add another constraint for the list size.
So, the improved macro can look like this:
define <keep_all_bits'struct_member> "keep_all_bits <list_size'num> <num'name> <list_name'name>" as computed {
result = appendf("keep %s.size() == %s;", <list_name'name>, <list_size'num>);
for i from 0 to (<list_size'num>.as_a(int) - 1) do {
result = appendf("%s keep %s[%d] == %s[%d:%d];",result, <list_name'name>, i, <num'name>, i, i);
};
};
Why not write is without macro?
keep for each in list_of_bits {
it == foo[index:index];
};
This should do the same, but look more readable and easier to debug; also the generation engine might take some advantage of more concise constraint.