1: function foo(){} foo(); // calls foo 2: foo = function(){}; foo(); // calls foo 3: ( function(){} )(); // calls the anonymous function
Wednesday, April 24, 2013
JavaScript alphabet song
If JavaScript has an alphabet or elementary song, I think this is the one:
Objective C's C#'s lambda
So we are missing C#'s Where lambda, which allows us to generalize a filter pattern, instead of creating new function everytime we need a new kind filter. On my last post about C#'s extension method, we have defined a function that filters all the odd elements, and everytime we have a new kind of filter, say get all the even elements, we will need to introduce another method called evenElements, think of all possible variations of filter and duplicated amount of code in those functions.
How about instead of creating a new method whenever a new set of condition would be required, we generalize the method's functionality and allows us to pass any kind of filters.
Luckily for C# transitioners, Objective C has a lambda, which is called blocks.
So with blocks, it allows us to create building blocks for generalized routine, e.g. filter.
So instead of creating another method that filters all the even numbers, we will just create a generalized lambda method that allows us to pass any filter condition. First, we should create the signature of the lambda in the .h file:
This is the lambda parameter on NSMutableArray's where Category(Extension Method in C#'s parlance):
In Objective-C, the method's parameter has the following syntax, open parenthesis, type, close parenthesis, and the name of the parameter. So the name of the parameter is expr. So our type is:
The caret(^) denotes that the type is a lambda type, and that lambda signature allows us to receive an NSNumber parameter, and allows us to return a boolean type. So that's just it. Can't take but notice that it's a bit ironic that given the Objective-C's messaging mechanism (where the message's parameter is denoted by a colon), its lambda syntax takes the function signature form (similar to JavaScript lambda or C#'s Func/delegate) instead of its usual messaging mechanism syntax. I think Objective-C lambda code will look very convoluted if its lambda syntax resembles Objective-C messaging rather than the simpler function signature.
Here's the implementation of the lambda signature above, note that we simply invoke the expr by adding an open parenthesis, parameter, and close parenthesis. Which is a homey function syntax, not the messaging style syntax of Objective-C
If you are curious, yes this doesn't work:
Then here's how we use the lambda implementation:
Output:
We want to list all odd numbers less than 100?
How about instead of creating a new method whenever a new set of condition would be required, we generalize the method's functionality and allows us to pass any kind of filters.
Luckily for C# transitioners, Objective C has a lambda, which is called blocks.
So with blocks, it allows us to create building blocks for generalized routine, e.g. filter.
So instead of creating another method that filters all the even numbers, we will just create a generalized lambda method that allows us to pass any filter condition. First, we should create the signature of the lambda in the .h file:
-(NSMutableArray*) where: (bool (^)(NSNumber *)) expr;
This is the lambda parameter on NSMutableArray's where Category(Extension Method in C#'s parlance):
(bool (^)(NSNumber *)) expr;
In Objective-C, the method's parameter has the following syntax, open parenthesis, type, close parenthesis, and the name of the parameter. So the name of the parameter is expr. So our type is:
bool (^)(NSNumber *)
The caret(^) denotes that the type is a lambda type, and that lambda signature allows us to receive an NSNumber parameter, and allows us to return a boolean type. So that's just it. Can't take but notice that it's a bit ironic that given the Objective-C's messaging mechanism (where the message's parameter is denoted by a colon), its lambda syntax takes the function signature form (similar to JavaScript lambda or C#'s Func/delegate) instead of its usual messaging mechanism syntax. I think Objective-C lambda code will look very convoluted if its lambda syntax resembles Objective-C messaging rather than the simpler function signature.
Here's the implementation of the lambda signature above, note that we simply invoke the expr by adding an open parenthesis, parameter, and close parenthesis. Which is a homey function syntax, not the messaging style syntax of Objective-C
-(NSMutableArray*) where: (bool (^)(NSNumber *)) expr { NSMutableArray *x = [NSMutableArray array]; for(NSNumber *number in self) { if (expr(number)) { // we invoke the expr lambda [x addObject: number]; } } return x; }
If you are curious, yes this doesn't work:
if ([expr number]) { [x addObject: number]; }
Then here's how we use the lambda implementation:
void demoArray() { @autoreleasepool { NSMutableArray *items = [NSMutableArray array]; [items addObject: [NSNumber numberWithInteger:42]]; [items addObject: [NSNumber numberWithInteger:11]]; [items addObject: [NSNumber numberWithInteger:5]]; [items addObject: [NSNumber numberWithInteger:1976]]; for(NSNumber *number in [items oddElements]) { printf("\n%d", number.intValue); } printf("All even numbers:\n"); for(NSNumber *number in [items where: ^(NSNumber *n) { return (bool)(n.intValue % 2 == 0 ); } ]) { printf("\n%d", number.intValue); } } }
Output:
All even numbers: 42 1976
We want to list all odd numbers less than 100?
void demoArray() { @autoreleasepool { NSMutableArray *items = [NSMutableArray array]; [items addObject: [NSNumber numberWithInteger:42]]; [items addObject: [NSNumber numberWithInteger:11]]; [items addObject: [NSNumber numberWithInteger:5]]; [items addObject: [NSNumber numberWithInteger:1976]]; for(NSNumber *number in [items where: ^(NSNumber *n) { return (bool)(n.intValue % 2 == 1 && n.intValue <= 100 ); } ]) { printf("\n%d", number.intValue); } } }Output:
11 5
Saturday, April 20, 2013
Objective-C's C# Extension Method
...is called Categories.
NSMutableArray+Selector.h:
NSMutableArray+Selector.m
To use the categories:
NSMutableArray+Selector.h:
#import <Foundation/Foundation.h> @interface NSMutableArray (Selector) -(NSMutableArray*) oddElements; @end
NSMutableArray+Selector.m
#import "NSMutableArray+Selector.h" @implementation NSMutableArray (Selector) -(NSMutableArray *) oddElements { NSMutableArray *x = [NSMutableArray array]; for(NSNumber *number in self) { if (number.intValue % 2 == 1) { [x addObject: number]; } } return x; } @end
To use the categories:
#include <CoreFoundation/CoreFoundation.h> #include "ThePerson.h" #include "NSMutableArray+Selector.h" void demoArray() { @autoreleasepool { NSMutableArray *items = [NSMutableArray array]; [items addObject: [NSNumber numberWithInteger:42]]; [items addObject: [NSNumber numberWithInteger:11]]; [items addObject: [NSNumber numberWithInteger:5]]; [items addObject: [NSNumber numberWithInteger:1976]]; for(NSNumber *number in [items oddElements]) { printf("\n%d", number.intValue); } } } int main(int argc, const char * argv[]) { demoArray(); return 0; }
List in Objective-C
void demoArray() { @autoreleasepool { NSMutableArray *items = [NSMutableArray array]; [items addObject: [NSNumber numberWithInteger:42]]; [items addObject: [NSNumber numberWithInteger:11]]; [items addObject: [NSNumber numberWithInteger:5]]; [items addObject: [NSNumber numberWithInteger:1976]]; for(NSNumber *number in items) { printf("\n%d", number.intValue); } } }
Wednesday, April 17, 2013
Objective C's C# auto-implemented properties
Missing C#'s auto-implemented properties?
For the uninitiated, here's what auto-implemented properties in C# looks like:
That syntax spares the developer from incessant creations of backing field for property and explicitly coding the property's getter and setter
Writing that things over and over easily gets old, hence the creation of auto-implemented properties in the language. Auto-implemented properties creates codes for you behind-the-scenes, rather than the you writing the repetitive and boring stuff
Objective-C has analogous mechanism to that C#'s auto-implemented property
ThePerson.h:
ThePerson.m:
It behaves exactly the same as in C#, i.e. you don't have to write explicit setter and getter code for your property. And you can still use the property as if dot notation was not invented, i.e. you can still invoke its setter explicitly [objectInstanceHere setHatedNumber]
Happy Computing! ツ
UPDATE
On Xcode 4.4, synthesize keyword is not needed anymore when creating automatic properties, and by default it automatically creates a backing field for your property, which name is prefixed by an underscore followed by the property name. I would prefer it not exposing any backing field, just like with the automatic property in C#
For the uninitiated, here's what auto-implemented properties in C# looks like:
public class ThePerson { public int HatedNumber {get; set;} }
That syntax spares the developer from incessant creations of backing field for property and explicitly coding the property's getter and setter
public class The Person { int _hatedNumber; public int HatedNumber { get { return _hatedNumber; } set { _hatedNumber = hatedNumber; } }
Writing that things over and over easily gets old, hence the creation of auto-implemented properties in the language. Auto-implemented properties creates codes for you behind-the-scenes, rather than the you writing the repetitive and boring stuff
Objective-C has analogous mechanism to that C#'s auto-implemented property
ThePerson.h:
#import *<Cocoa/Cocoa.h> @interface ThePerson : NSObject { } @property int hatedNumber; @end
ThePerson.m:
#import "ThePerson.h" @implementation ThePerson @synthesize hatedNumber; @end
It behaves exactly the same as in C#, i.e. you don't have to write explicit setter and getter code for your property. And you can still use the property as if dot notation was not invented, i.e. you can still invoke its setter explicitly [objectInstanceHere setHatedNumber]
#include <CoreFoundation/CoreFoundation.h> #include "ThePerson.h" int main(int argc, const char * argv[]) { // insert code here... ThePerson* p = [ThePerson new]; ThePerson* q = [ThePerson new]; ThePerson *x; x = p; [x setHatedNumber:4]; // classic way x = q; x.hatedNumber = 13; // modern way printf("%d\n", [p hatedNumber]); // classic way printf("%d\n", p.hatedNumber); // modern way printf("%d\n", [q hatedNumber]); // classic way printf("%d\n", q.hatedNumber); // modern way return 0; }
Happy Computing! ツ
UPDATE
On Xcode 4.4, synthesize keyword is not needed anymore when creating automatic properties, and by default it automatically creates a backing field for your property, which name is prefixed by an underscore followed by the property name. I would prefer it not exposing any backing field, just like with the automatic property in C#
Tuesday, April 16, 2013
Objective C's class and property
main.m
The class mechanism for Objective C uses the interface keyword. Then we put the backing field inside the curly bracket. And all the method signature after the curly bracket.
Person.h
Person.m
#include <CoreFoundation/CoreFoundation.h> #include "ThePerson.h" int main(int argc, const char * argv[]) { // insert code here... ThePerson* p = [ThePerson new]; ThePerson* q = [ThePerson new]; ThePerson *x; x = p; [x setFavoriteNumber:7]; // classic way x = q; x.favoriteNumber = 6; // modern. neater syntax, lesser friction. calls the method setFavoriteNumber printf("%d\n", [p favoriteNumber]); // classic way printf("%d\n", p.favoriteNumber); // modern way printf("%d\n", [q favoriteNumber]); // classic way printf("%d\n", q.favoriteNumber); // modern way return 0; }
The class mechanism for Objective C uses the interface keyword. Then we put the backing field inside the curly bracket. And all the method signature after the curly bracket.
Person.h
#import <Cocoa/Cocoa.h> @interface ThePerson : NSObject { int _favoriteNumber; } -(int) favoriteNumber; -(void) setFavoriteNumber: (int) input; @end
Person.m
#import "ThePerson.h" @implementation ThePerson -(int)favoriteNumber { return _favoriteNumber; } -(void) setFavoriteNumber:(int)input { printf("Set is Called\n"); _favoriteNumber = input; } @end
Monday, April 15, 2013
Remove breakpoint in Objective-C
Drag and drop the breakpoint anywhere, and poof!
http://stackoverflow.com/questions/10016890/thread-1-stopped-at-breakpoint-error-when-initializing-an-nsurl-object/10016939#10016939
http://stackoverflow.com/questions/10016890/thread-1-stopped-at-breakpoint-error-when-initializing-an-nsurl-object/10016939#10016939
Sunday, April 7, 2013
Gaps to islands
On an old post, I discussed how island and gaps algorithms work: http://www.anicehumble.com/2012/08/monitoring-perfect-attendance.html
On this post, I will discuss the exact reverse of that.
Given the following data:
Requirement is to cluster those gaps together:
The easiest way to solve that is to use windowing function, i.e. use first_value on each group. First thing first, we must devise a way to group those gaps together. We can do that by counting over the id's order. COUNT doesn't count nulls, hence COUNT will be able to group nulls to a previous non-null, COUNT will maintain the same count as long as it is encountering nulls. To illustrate:
Output:
Now that we designated a grouping number for related data, getting the first value among the group shall just be a simple undertaking, use first_value from the partition of grp
Output:
On this post, I will discuss the exact reverse of that.
Given the following data:
CREATE TABLE y ("id" int, "val" varchar(1)) ; INSERT INTO y ("id", "val") VALUES (1, 'a'), (4, 'b') ; CREATE TABLE x ("id" int) ; INSERT INTO x ("id") VALUES (1), (2), (3), (4), (5) ; with z as ( select x.id, y.val from x left join y on y.id = x.id ) select * from z order by id ;
| ID | VAL | --------------- | 1 | a | | 2 | (null) | | 3 | (null) | | 4 | b | | 5 | (null) |
Requirement is to cluster those gaps together:
| ID | VAL | ------------ | 1 | a | | 2 | a | | 3 | a | | 4 | b | | 5 | b |
The easiest way to solve that is to use windowing function, i.e. use first_value on each group. First thing first, we must devise a way to group those gaps together. We can do that by counting over the id's order. COUNT doesn't count nulls, hence COUNT will be able to group nulls to a previous non-null, COUNT will maintain the same count as long as it is encountering nulls. To illustrate:
with z as ( select x.id, y.val, count(y.val) over(order by x.id ) as grp from x left join y on y.id = x.id ) select * from z order by id ;
Output:
| ID | VAL | GRP | --------------------- | 1 | a | 1 | | 2 | (null) | 1 | | 3 | (null) | 1 | | 4 | b | 2 | | 5 | (null) | 2 |
Now that we designated a grouping number for related data, getting the first value among the group shall just be a simple undertaking, use first_value from the partition of grp
with z as ( select x.id, y.val, count(y.val) over(order by x.id ) as grp from x left join y on y.id = x.id ) select id, val, grp, first_value(val) over(partition by grp order by id) from z;
Output:
| ID | VAL | GRP | FIRST_VALUE | ----------------------------------- | 1 | a | 1 | a | | 2 | (null) | 1 | a | | 3 | (null) | 1 | a | | 4 | b | 2 | b | | 5 | (null) | 2 | b |
Saturday, April 6, 2013
MVCC
Entity Framework 6 database creation defaults to MVCC now:
Default transaction isolation level is changed to READ_COMMITTED_SNAPSHOT for databases created using Code First, potentially allowing for more scalability and fewer deadlocks. -- http://entityframework.codeplex.com/wikipage?title=specs
On related news:
Want to see an SQL Server DBA nerdgasm'd? Let him/her use Postgresql, it's an RDBMS (that like Oracle) on which the supported concurrency model is MVCC, so you'll get fewer deadlocks on your database:
http://www.youtube.com/watch?v=Rl_-lKxSBm4
Is your database OOP-deprived? See the demo of inheritance using Postgresql on the video above
Microsoft uses Postgresql too, we know Microsoft bought Skype. Skype uses Postgresql
Instagram uses Postgresql too
Default transaction isolation level is changed to READ_COMMITTED_SNAPSHOT for databases created using Code First, potentially allowing for more scalability and fewer deadlocks. -- http://entityframework.codeplex.com/wikipage?title=specs
On related news:
Want to see an SQL Server DBA nerdgasm'd? Let him/her use Postgresql, it's an RDBMS (that like Oracle) on which the supported concurrency model is MVCC, so you'll get fewer deadlocks on your database:
http://www.youtube.com/watch?v=Rl_-lKxSBm4
Is your database OOP-deprived? See the demo of inheritance using Postgresql on the video above
Microsoft uses Postgresql too, we know Microsoft bought Skype. Skype uses Postgresql
Instagram uses Postgresql too
Subscribe to:
Posts (Atom)