diff options
-rw-r--r-- | c.html.markdown | 4 | ||||
-rw-r--r-- | hy.html.markdown | 174 | ||||
-rw-r--r-- | objective-c.html.markdown | 78 | ||||
-rw-r--r-- | zh-cn/javascript-cn.html.markdown | 2 |
4 files changed, 245 insertions, 13 deletions
diff --git a/c.html.markdown b/c.html.markdown index 84856b32..e55ff148 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -92,7 +92,7 @@ int main() { printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - // If the argument of the `sizeof` operator an expression, then its argument + // If the argument of the `sizeof` operator is an expression, then its argument // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. int a = 1; @@ -376,7 +376,7 @@ int main() { // or when it's the argument of the `sizeof` or `alignof` operator: int arr[10]; int *ptr = arr; // equivalent with int *ptr = &arr[0]; - printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" + printf("%zu, %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type diff --git a/hy.html.markdown b/hy.html.markdown new file mode 100644 index 00000000..04bd05c9 --- /dev/null +++ b/hy.html.markdown @@ -0,0 +1,174 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +--- + +Hy is a lisp dialect built on top of python. This is achieved by +converting hy code to python's abstract syntax tree (ast). This allows +hy to call native python code or python to call native hy code as well + +This tutorial works for hy ≥ 0.9.12 + +```clojure +;; this gives an gentle introduction to hy for a quick trial head to +;; http://try-hy.appspot.com +;; +; Semicolon comments, like other LISPS + +;; s-expression basics +; lisp programs are made of symbolic expressions or sexps which +; resemble +(some-function args) +; now the quintessential hello world +(print "hello world") + +;; simple data types +; All simple data types are exactly similar to their python counterparts +; which +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) a complex number + +; lets start with some really simple arithmetic +(+ 4 1) ;=> 5 +; the operator is applied to all arguments, like other lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 the modulo operator +; power is represented by ** operator like python +(** 3 2) ;=> 9 +; nesting forms will do the expected thing +(+ 2 (* 4 2)) ;=> 10 +; also logical operators and or not and equal to etc. do as expected +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variables +; variables are set using setv, variable names can use utf-8 except +; for ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; other container data types +; strings, lists, tuples & dicts +; these are exactly same as python's container types +"hello world" ;=> "hello world" +; string operations work similar to python +(+ "hello " "world") ;=> "hello world" +; lists are created using [], indexing starts at 0 +(setv mylist [1 2 3 4]) +; tuples are immutable data structures +(setv mytuple (, 1 2)) +; dictionaries are key value pairs +(setv dict1 {"key1" 42 "key2" 21}) +; :name can be used to define keywords in hy which can be used for keys +(setv dict2 {:key1 41 :key2 20}) +; use `get' to get the element at an index/key +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternatively if keywords were used they can directly be called +(:key1 dict2) ;=> 41 + +;; functions and other program constructs +; functions are defined using defn, the last sexp is returned by default +(defn greet [name] + "A simple greeting" ; an optional docstring + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; functions can take optional arguments as well as keyword arguments +(defn foolist [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; anonymous functions are created using `fn' or `lambda' constructs +; which are similiar to `defn' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; Sequence operations +; hy has some builtin utils for sequence operations etc. +; retrieve the first element using `first' or `car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; slice lists using slice +(slice mylist 1 3) ;=> [2 3] + +; get elements from a list or dict using `get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; list indexing starts from 0 same as python +; assoc can set elements at keys/indexes +(assoc mylist 2 10) ; makes mylist [1 2 10 4] +(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3} +; there are a whole lot of other core functions which makes working with +; sequences fun + +;; Python interop +;; import works just like in python +(import datetime) +(import [functools [partial reduce]]) ; imports fun1 and fun2 from module1 +(import [matplotlib.pyplot :as plt]) ; doing an import foo as bar +; all builtin python methods etc. are accessible from hy +; a.foo(arg) is called as (.foo a arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Conditionals +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; nest multiple if else if clauses with cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; group statements with do, these are executed sequentially +; forms like defn have an implicit do +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; create lexical bindings with `let', all variables defined thusly +; have local scope +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; classes are defined in the following way +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init the spell attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; do checkout hylang.org +``` + +### Further Reading + +This tutorial is just a very basic introduction to hy/lisp/python. + +Hy docs are here: [http://hy.readthedocs.org](http://hy.readthedocs.org) + +Hy's Github repo: [http://github.com/hylang/hy](http://github.com/hylang/hy) + +On freenode irc #hy, twitter hashtag #hylang diff --git a/objective-c.html.markdown b/objective-c.html.markdown index a70351b5..f2787649 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -297,22 +297,28 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter method name = 'setCount' -@property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Cannot set value outside interface. +@property int propInt; // Setter method name = 'setPropInt' +@property (copy) id copyId; // (copy) => Copy the object during assignment. +// (readonly) => Cannot set value outside @interface. +@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -// + for class method +// + for class methods: + (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - for instance method +// - for instance methods: - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; +// Constructor methods with arguments: +- (id)initWithDistance:(int)defaultDistance; +// Objective-C method names are very descriptive. Always name methods according to their arguments. + @end // States the end of the interface. @@ -328,38 +334,86 @@ NSLog(@"%i", [myClass lengthGet]); // prints => 32 myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Call class methods: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Call instance methods: +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + +// Selectors. +// Way to dynamically represent methods. Used to call methods of a class, pass methods +// through functions to tell other classes they should call it, and to save methods +// as a variable. +// SEL is the data type. @selector() returns a selector from method name provided. +// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. + // Must put all method arguments into one object to send to performSelector function. + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method. +} else { + // NSStringFromSelector() returns a NSString of the method name of a given selector. + NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); +} // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. + NSNumber height; } // To access a public variable from the interface file, use '_' followed by variable name: _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation. + +// Called before calling any class methods or instantiating any objects. ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} -// Call when the object is releasing +// Counterpart to initialize method. Called when an object's reference count is zero. - (void)dealloc { + [height release]; // If not using ARC, make sure to release class variable objects + [super dealloc]; // and call parent class dealloc. } -// Constructors are a way of creating classes +// Constructors are a way of creating instances of a class. // This is a default constructor which is called when the object is initialized. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' used to access methods from parent class. { - self.count = 1; + self.count = 1; // 'self' used for object to call itself. } return self; } +// Can create constructors that contain arguments: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { return @"New string"; @@ -370,6 +424,12 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } +// To create a private method, create the method in the @implementation but not in the @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method. + // Methods declared into MyProtocol - (void)myProtocolMethod { diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 89fc256e..86ad1d07 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -401,8 +401,6 @@ if (Object.create === undefined){ // 如果存在则不覆盖 [Mozilla 开发者 网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 -wiki, so as you learn more you can help others out by sharing your own -knowledge. MDN的 [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) |