mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-22 23:01:41 +03:00
removing whitespace all over
This commit is contained in:
parent
a793d16e37
commit
960ee4a185
@ -8,10 +8,10 @@ filename: learnamd.js
|
|||||||
|
|
||||||
## Getting Started with AMD
|
## Getting Started with AMD
|
||||||
|
|
||||||
The **Asynchronous Module Definition** API specifies a mechanism for defining
|
The **Asynchronous Module Definition** API specifies a mechanism for defining
|
||||||
JavaScript modules such that the module and its dependencies can be asynchronously
|
JavaScript modules such that the module and its dependencies can be asynchronously
|
||||||
loaded. This is particularly well suited for the browser environment where
|
loaded. This is particularly well suited for the browser environment where
|
||||||
synchronous loading of modules incurs performance, usability, debugging, and
|
synchronous loading of modules incurs performance, usability, debugging, and
|
||||||
cross-domain access problems.
|
cross-domain access problems.
|
||||||
|
|
||||||
### Basic concept
|
### Basic concept
|
||||||
|
@ -72,45 +72,45 @@ for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arb
|
|||||||
you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0),
|
you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0),
|
||||||
`f(n)` <= `c g(n)` for every input size n (n > 0).
|
`f(n)` <= `c g(n)` for every input size n (n > 0).
|
||||||
|
|
||||||
*Example 1*
|
*Example 1*
|
||||||
|
|
||||||
```
|
```
|
||||||
f(n) = 3log n + 100
|
f(n) = 3log n + 100
|
||||||
g(n) = log n
|
g(n) = log n
|
||||||
```
|
```
|
||||||
|
|
||||||
Is `f(n)` O(g(n))?
|
Is `f(n)` O(g(n))?
|
||||||
Is `3 log n + 100` O(log n)?
|
Is `3 log n + 100` O(log n)?
|
||||||
Let's look to the definition of Big-O.
|
Let's look to the definition of Big-O.
|
||||||
|
|
||||||
```
|
```
|
||||||
3log n + 100 <= c * log n
|
3log n + 100 <= c * log n
|
||||||
```
|
```
|
||||||
|
|
||||||
Is there some constant c that satisfies this for all n?
|
Is there some constant c that satisfies this for all n?
|
||||||
|
|
||||||
```
|
```
|
||||||
3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1)
|
3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1)
|
||||||
```
|
```
|
||||||
|
|
||||||
Yes! The definition of Big-O has been met therefore `f(n)` is O(g(n)).
|
Yes! The definition of Big-O has been met therefore `f(n)` is O(g(n)).
|
||||||
|
|
||||||
*Example 2*
|
*Example 2*
|
||||||
|
|
||||||
```
|
```
|
||||||
f(n) = 3*n^2
|
f(n) = 3*n^2
|
||||||
g(n) = n
|
g(n) = n
|
||||||
```
|
```
|
||||||
|
|
||||||
Is `f(n)` O(g(n))?
|
Is `f(n)` O(g(n))?
|
||||||
Is `3 * n^2` O(n)?
|
Is `3 * n^2` O(n)?
|
||||||
Let's look at the definition of Big-O.
|
Let's look at the definition of Big-O.
|
||||||
|
|
||||||
```
|
```
|
||||||
3 * n^2 <= c * n
|
3 * n^2 <= c * n
|
||||||
```
|
```
|
||||||
|
|
||||||
Is there some constant c that satisfies this for all n?
|
Is there some constant c that satisfies this for all n?
|
||||||
No, there isn't. `f(n)` is NOT O(g(n)).
|
No, there isn't. `f(n)` is NOT O(g(n)).
|
||||||
|
|
||||||
### Big-Omega
|
### Big-Omega
|
||||||
|
@ -252,7 +252,7 @@ grep "^foo.*bar$" file.txt
|
|||||||
grep -c "^foo.*bar$" file.txt
|
grep -c "^foo.*bar$" file.txt
|
||||||
# if you literally want to search for the string,
|
# if you literally want to search for the string,
|
||||||
# and not the regex, use fgrep (or grep -F)
|
# and not the regex, use fgrep (or grep -F)
|
||||||
fgrep "^foo.*bar$" file.txt
|
fgrep "^foo.*bar$" file.txt
|
||||||
|
|
||||||
|
|
||||||
# Read Bash shell builtins documentation with the bash 'help' builtin:
|
# Read Bash shell builtins documentation with the bash 'help' builtin:
|
||||||
|
@ -307,7 +307,7 @@ var stringSet: domain(string); // empty set of strings
|
|||||||
stringSet += "a";
|
stringSet += "a";
|
||||||
stringSet += "b";
|
stringSet += "b";
|
||||||
stringSet += "c";
|
stringSet += "c";
|
||||||
stringSet += "a"; // Redundant add "a"
|
stringSet += "a"; // Redundant add "a"
|
||||||
stringSet -= "c"; // Remove "c"
|
stringSet -= "c"; // Remove "c"
|
||||||
writeln( stringSet );
|
writeln( stringSet );
|
||||||
|
|
||||||
@ -524,12 +524,12 @@ genericProc( 1.0+2.0i, 3.0+4.0i );
|
|||||||
// The param modifier on the arg is used to enforce this constraint.
|
// The param modifier on the arg is used to enforce this constraint.
|
||||||
proc whereProc( param N : int ): void
|
proc whereProc( param N : int ): void
|
||||||
where ( N > 0 ) {
|
where ( N > 0 ) {
|
||||||
writeln( "N is greater than 0" );
|
writeln( "N is greater than 0" );
|
||||||
}
|
}
|
||||||
|
|
||||||
proc whereProc( param N : int ): void
|
proc whereProc( param N : int ): void
|
||||||
where ( N < 0 ) {
|
where ( N < 0 ) {
|
||||||
writeln( "N is less than 0" );
|
writeln( "N is less than 0" );
|
||||||
}
|
}
|
||||||
|
|
||||||
whereProc( 10 );
|
whereProc( 10 );
|
||||||
|
@ -142,11 +142,11 @@ You'll want to be familiar with Clojure. Make sure you understand everything in
|
|||||||
|
|
||||||
### Further Reading
|
### Further Reading
|
||||||
|
|
||||||
Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/)
|
Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/)
|
||||||
[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
|
[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
|
||||||
|
|
||||||
Official docs
|
Official docs
|
||||||
[http://clojure.org/macros](http://clojure.org/macros)
|
[http://clojure.org/macros](http://clojure.org/macros)
|
||||||
|
|
||||||
When to use macros?
|
When to use macros?
|
||||||
[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
|
[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
|
||||||
|
@ -6,7 +6,7 @@ contributors:
|
|||||||
filename: coffeescript.coffee
|
filename: coffeescript.coffee
|
||||||
---
|
---
|
||||||
|
|
||||||
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
|
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
|
||||||
As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
|
As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
|
||||||
|
|
||||||
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
|
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
|
||||||
@ -73,7 +73,7 @@ alert "I knew it!" if elvis?
|
|||||||
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
|
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
|
||||||
|
|
||||||
# Array comprehensions:
|
# Array comprehensions:
|
||||||
cubes = (math.cube num for num in list)
|
cubes = (math.cube num for num in list)
|
||||||
#=>cubes = (function() {
|
#=>cubes = (function() {
|
||||||
# var _i, _len, _results;
|
# var _i, _len, _results;
|
||||||
# _results = [];
|
# _results = [];
|
||||||
|
@ -261,7 +261,7 @@ nil ; for false - and the empty list
|
|||||||
|
|
||||||
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
|
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
|
||||||
:adjustable t :fill-pointer t))
|
:adjustable t :fill-pointer t))
|
||||||
|
|
||||||
*adjvec* ; => #(1 2 3)
|
*adjvec* ; => #(1 2 3)
|
||||||
|
|
||||||
;; Adding new element:
|
;; Adding new element:
|
||||||
|
@ -25,7 +25,7 @@ Multi-line comments look like this
|
|||||||
//public void MethodOrClassOrOtherWithParsableHelp() {}
|
//public void MethodOrClassOrOtherWithParsableHelp() {}
|
||||||
|
|
||||||
// Specify the namespaces this source code will be using
|
// Specify the namespaces this source code will be using
|
||||||
// The namespaces below are all part of the standard .NET Framework Class Libary
|
// The namespaces below are all part of the standard .NET Framework Class Libary
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Dynamic;
|
using System.Dynamic;
|
||||||
@ -48,7 +48,7 @@ namespace Learning.CSharp
|
|||||||
public class LearnCSharp
|
public class LearnCSharp
|
||||||
{
|
{
|
||||||
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
|
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
|
||||||
public static void Syntax()
|
public static void Syntax()
|
||||||
{
|
{
|
||||||
// Use Console.WriteLine to print lines
|
// Use Console.WriteLine to print lines
|
||||||
Console.WriteLine("Hello World");
|
Console.WriteLine("Hello World");
|
||||||
@ -371,11 +371,11 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
//
|
//
|
||||||
// INTERESTING FEATURES
|
// INTERESTING FEATURES
|
||||||
//
|
//
|
||||||
|
|
||||||
// DEFAULT METHOD SIGNATURES
|
// DEFAULT METHOD SIGNATURES
|
||||||
|
|
||||||
public // Visibility
|
public // Visibility
|
||||||
static // Allows for direct call on class without object
|
static // Allows for direct call on class without object
|
||||||
int // Return Type,
|
int // Return Type,
|
||||||
MethodSignatures(
|
MethodSignatures(
|
||||||
int maxCount, // First variable, expects an int
|
int maxCount, // First variable, expects an int
|
||||||
@ -383,7 +383,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
int another = 3,
|
int another = 3,
|
||||||
params string[] otherParams // captures all other parameters passed to method
|
params string[] otherParams // captures all other parameters passed to method
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -400,8 +400,8 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
// The classes for TKey and TValue is specified by the user calling this function.
|
// The classes for TKey and TValue is specified by the user calling this function.
|
||||||
// This method emulates the SetDefault of Python
|
// This method emulates the SetDefault of Python
|
||||||
public static TValue SetDefault<TKey, TValue>(
|
public static TValue SetDefault<TKey, TValue>(
|
||||||
IDictionary<TKey, TValue> dictionary,
|
IDictionary<TKey, TValue> dictionary,
|
||||||
TKey key,
|
TKey key,
|
||||||
TValue defaultItem)
|
TValue defaultItem)
|
||||||
{
|
{
|
||||||
TValue result;
|
TValue result;
|
||||||
@ -410,7 +410,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// You can narrow down the objects that are passed in
|
// You can narrow down the objects that are passed in
|
||||||
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
|
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
|
||||||
{
|
{
|
||||||
// We can iterate, since T is a IEnumerable
|
// We can iterate, since T is a IEnumerable
|
||||||
@ -450,13 +450,13 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
// GENERICS
|
// GENERICS
|
||||||
//
|
//
|
||||||
var phonebook = new Dictionary<string, string>() {
|
var phonebook = new Dictionary<string, string>() {
|
||||||
{"Sarah", "212 555 5555"} // Add some entries to the phone book
|
{"Sarah", "212 555 5555"} // Add some entries to the phone book
|
||||||
};
|
};
|
||||||
|
|
||||||
// Calling SETDEFAULT defined as a generic above
|
// Calling SETDEFAULT defined as a generic above
|
||||||
Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // No Phone
|
Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // No Phone
|
||||||
// nb, you don't need to specify the TKey and TValue since they can be
|
// nb, you don't need to specify the TKey and TValue since they can be
|
||||||
// derived implicitly
|
// derived implicitly
|
||||||
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
|
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
|
||||||
|
|
||||||
@ -491,26 +491,26 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
// DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
|
// DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
|
||||||
// Most of objects that access unmanaged resources (file handle, device contexts, etc.)
|
// Most of objects that access unmanaged resources (file handle, device contexts, etc.)
|
||||||
// implement the IDisposable interface. The using statement takes care of
|
// implement the IDisposable interface. The using statement takes care of
|
||||||
// cleaning those IDisposable objects for you.
|
// cleaning those IDisposable objects for you.
|
||||||
using (StreamWriter writer = new StreamWriter("log.txt"))
|
using (StreamWriter writer = new StreamWriter("log.txt"))
|
||||||
{
|
{
|
||||||
writer.WriteLine("Nothing suspicious here");
|
writer.WriteLine("Nothing suspicious here");
|
||||||
// At the end of scope, resources will be released.
|
// At the end of scope, resources will be released.
|
||||||
// Even if an exception is thrown.
|
// Even if an exception is thrown.
|
||||||
}
|
}
|
||||||
|
|
||||||
// PARALLEL FRAMEWORK
|
// PARALLEL FRAMEWORK
|
||||||
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
|
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
|
||||||
var websites = new string[] {
|
var websites = new string[] {
|
||||||
"http://www.google.com", "http://www.reddit.com",
|
"http://www.google.com", "http://www.reddit.com",
|
||||||
"http://www.shaunmccarthy.com"
|
"http://www.shaunmccarthy.com"
|
||||||
};
|
};
|
||||||
var responses = new Dictionary<string, string>();
|
var responses = new Dictionary<string, string>();
|
||||||
|
|
||||||
// Will spin up separate threads for each request, and join on them
|
// Will spin up separate threads for each request, and join on them
|
||||||
// before going to the next step!
|
// before going to the next step!
|
||||||
Parallel.ForEach(websites,
|
Parallel.ForEach(websites,
|
||||||
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
|
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
|
||||||
website =>
|
website =>
|
||||||
{
|
{
|
||||||
@ -534,7 +534,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
|
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
|
||||||
Console.WriteLine(student.Introduce("Beth"));
|
Console.WriteLine(student.Introduce("Beth"));
|
||||||
|
|
||||||
// IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
|
// IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
|
||||||
// very useful Map / Filter / Reduce style methods
|
// very useful Map / Filter / Reduce style methods
|
||||||
var bikes = new List<Bicycle>();
|
var bikes = new List<Bicycle>();
|
||||||
bikes.Sort(); // Sorts the array
|
bikes.Sort(); // Sorts the array
|
||||||
@ -556,8 +556,8 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
// ASPARALLEL
|
// ASPARALLEL
|
||||||
// And this is where things get wicked - combines linq and parallel operations
|
// And this is where things get wicked - combines linq and parallel operations
|
||||||
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
|
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
|
||||||
// this will happen in parallel! Threads will automagically be spun up and the
|
// this will happen in parallel! Threads will automagically be spun up and the
|
||||||
// results divvied amongst them! Amazing for large datasets when you have lots of
|
// results divvied amongst them! Amazing for large datasets when you have lots of
|
||||||
// cores
|
// cores
|
||||||
|
|
||||||
// LINQ - maps a store to IQueryable<T> objects, with delayed execution
|
// LINQ - maps a store to IQueryable<T> objects, with delayed execution
|
||||||
@ -575,9 +575,9 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
.Select(b => b.Name); // still no query run
|
.Select(b => b.Name); // still no query run
|
||||||
|
|
||||||
// Now the query runs, but opens a reader, so only populates are you iterate through
|
// Now the query runs, but opens a reader, so only populates are you iterate through
|
||||||
foreach (string bike in query)
|
foreach (string bike in query)
|
||||||
Console.WriteLine(result);
|
Console.WriteLine(result);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -629,7 +629,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
private set; // You can set modifiers on the get/set methods
|
private set; // You can set modifiers on the get/set methods
|
||||||
}
|
}
|
||||||
|
|
||||||
int _speed; // Everything is private by default: Only accessible from within this class.
|
int _speed; // Everything is private by default: Only accessible from within this class.
|
||||||
// can also use keyword private
|
// can also use keyword private
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
@ -676,7 +676,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
// Constructors are a way of creating classes
|
// Constructors are a way of creating classes
|
||||||
// This is a default constructor
|
// This is a default constructor
|
||||||
public Bicycle()
|
public Bicycle()
|
||||||
{
|
{
|
||||||
this.Gear = 1; // you can access members of the object with the keyword this
|
this.Gear = 1; // you can access members of the object with the keyword this
|
||||||
Cadence = 50; // but you don't always need it
|
Cadence = 50; // but you don't always need it
|
||||||
@ -688,13 +688,13 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
// This is a specified constructor (it contains arguments)
|
// This is a specified constructor (it contains arguments)
|
||||||
public Bicycle(int startCadence, int startSpeed, int startGear,
|
public Bicycle(int startCadence, int startSpeed, int startGear,
|
||||||
string name, bool hasCardsInSpokes, BikeBrand brand)
|
string name, bool hasCardsInSpokes, BikeBrand brand)
|
||||||
: base() // calls base first
|
: base() // calls base first
|
||||||
{
|
{
|
||||||
Gear = startGear;
|
Gear = startGear;
|
||||||
Cadence = startCadence;
|
Cadence = startCadence;
|
||||||
_speed = startSpeed;
|
_speed = startSpeed;
|
||||||
Name = name;
|
Name = name;
|
||||||
_hasCardsInSpokes = hasCardsInSpokes;
|
_hasCardsInSpokes = hasCardsInSpokes;
|
||||||
Brand = brand;
|
Brand = brand;
|
||||||
}
|
}
|
||||||
@ -857,7 +857,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Used to connect to DB for LinqToSql example.
|
/// Used to connect to DB for LinqToSql example.
|
||||||
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
|
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
|
||||||
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
|
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -882,7 +882,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
* ASP.NET Web Forms (old)
|
* ASP.NET Web Forms (old)
|
||||||
* WebMatrix (tool)
|
* WebMatrix (tool)
|
||||||
* Desktop Development
|
* Desktop Development
|
||||||
* Windows Presentation Foundation (WPF) (new)
|
* Windows Presentation Foundation (WPF) (new)
|
||||||
* Winforms (old)
|
* Winforms (old)
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
@ -8,19 +8,19 @@ contributors:
|
|||||||
filename: learncss.css
|
filename: learncss.css
|
||||||
---
|
---
|
||||||
|
|
||||||
In the early days of the web there were no visual elements, just pure text. But with the
|
In the early days of the web there were no visual elements, just pure text. But with the
|
||||||
further development of browsers, fully visual web pages also became common.
|
further development of browsers, fully visual web pages also became common.
|
||||||
CSS is the standard language that exists to keep the separation between
|
CSS is the standard language that exists to keep the separation between
|
||||||
the content (HTML) and the look-and-feel of web pages.
|
the content (HTML) and the look-and-feel of web pages.
|
||||||
|
|
||||||
In short, what CSS does is to provide a syntax that enables you to target
|
In short, what CSS does is to provide a syntax that enables you to target
|
||||||
different elements on an HTML page and assign different visual properties to them.
|
different elements on an HTML page and assign different visual properties to them.
|
||||||
|
|
||||||
Like any other languages, CSS has many versions. Here we focus on CSS2.0,
|
Like any other languages, CSS has many versions. Here we focus on CSS2.0,
|
||||||
which is not the most recent version, but is the most widely supported and compatible version.
|
which is not the most recent version, but is the most widely supported and compatible version.
|
||||||
|
|
||||||
**NOTE:** Because the outcome of CSS consists of visual effects, in order to
|
**NOTE:** Because the outcome of CSS consists of visual effects, in order to
|
||||||
learn it, you need try everything in a
|
learn it, you need try everything in a
|
||||||
CSS playground like [dabblet](http://dabblet.com/).
|
CSS playground like [dabblet](http://dabblet.com/).
|
||||||
The main focus of this article is on the syntax and some general tips.
|
The main focus of this article is on the syntax and some general tips.
|
||||||
|
|
||||||
@ -78,8 +78,8 @@ div { }
|
|||||||
[otherAttr|='en'] { font-size:smaller; }
|
[otherAttr|='en'] { font-size:smaller; }
|
||||||
|
|
||||||
|
|
||||||
/* and more importantly you can combine these together -- there shouldn't be
|
/* and more importantly you can combine these together -- there shouldn't be
|
||||||
any space between different parts because that makes it to have another
|
any space between different parts because that makes it to have another
|
||||||
meaning. */
|
meaning. */
|
||||||
div.some-class[attr$='ue'] { }
|
div.some-class[attr$='ue'] { }
|
||||||
|
|
||||||
@ -89,22 +89,22 @@ div.some-class[attr$='ue'] { }
|
|||||||
div.some-parent > .class-name {}
|
div.some-parent > .class-name {}
|
||||||
|
|
||||||
/* or any of its parents in the tree
|
/* or any of its parents in the tree
|
||||||
the following basically means any element that has class "class-name"
|
the following basically means any element that has class "class-name"
|
||||||
and is child of a div with class name "some-parent" IN ANY DEPTH */
|
and is child of a div with class name "some-parent" IN ANY DEPTH */
|
||||||
div.some-parent .class-name {}
|
div.some-parent .class-name {}
|
||||||
|
|
||||||
/* warning: the same selector without space has another meaning.
|
/* warning: the same selector without space has another meaning.
|
||||||
can you say what? */
|
can you say what? */
|
||||||
div.some-parent.class-name {}
|
div.some-parent.class-name {}
|
||||||
|
|
||||||
/* you also might choose to select an element based on its direct
|
/* you also might choose to select an element based on its direct
|
||||||
previous sibling */
|
previous sibling */
|
||||||
.i-am-before + .this-element { }
|
.i-am-before + .this-element { }
|
||||||
|
|
||||||
/* or any sibling before this */
|
/* or any sibling before this */
|
||||||
.i-am-any-before ~ .this-element {}
|
.i-am-any-before ~ .this-element {}
|
||||||
|
|
||||||
/* There are some pseudo classes that allows you to select an element
|
/* There are some pseudo classes that allows you to select an element
|
||||||
based on its page behaviour (rather than page structure) */
|
based on its page behaviour (rather than page structure) */
|
||||||
|
|
||||||
/* for example for when an element is hovered */
|
/* for example for when an element is hovered */
|
||||||
@ -125,7 +125,7 @@ selected:focus {}
|
|||||||
#################### */
|
#################### */
|
||||||
|
|
||||||
selector {
|
selector {
|
||||||
|
|
||||||
/* Units */
|
/* Units */
|
||||||
width: 50%; /* in percent */
|
width: 50%; /* in percent */
|
||||||
font-size: 2em; /* times current font-size */
|
font-size: 2em; /* times current font-size */
|
||||||
@ -138,7 +138,7 @@ selector {
|
|||||||
width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */
|
width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */
|
||||||
min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */
|
min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */
|
||||||
max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */
|
max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */
|
||||||
|
|
||||||
/* Colors */
|
/* Colors */
|
||||||
background-color: #F6E; /* in short hex */
|
background-color: #F6E; /* in short hex */
|
||||||
background-color: #F262E2; /* in long hex format */
|
background-color: #F262E2; /* in long hex format */
|
||||||
@ -150,10 +150,10 @@ selector {
|
|||||||
background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */
|
background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */
|
||||||
background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */
|
background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */
|
||||||
|
|
||||||
|
|
||||||
/* Images */
|
/* Images */
|
||||||
background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
|
background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
|
||||||
|
|
||||||
/* Fonts */
|
/* Fonts */
|
||||||
font-family: Arial;
|
font-family: Arial;
|
||||||
font-family: "Courier New"; /* if name has space it appears in single or double quotes */
|
font-family: "Courier New"; /* if name has space it appears in single or double quotes */
|
||||||
@ -171,13 +171,13 @@ Save any CSS you want in a file with extension `.css`.
|
|||||||
<!-- you need to include the css file in your page's <head>: -->
|
<!-- you need to include the css file in your page's <head>: -->
|
||||||
<link rel='stylesheet' type='text/css' href='path/to/style.css' />
|
<link rel='stylesheet' type='text/css' href='path/to/style.css' />
|
||||||
|
|
||||||
<!-- you can also include some CSS inline in your markup. However it is highly
|
<!-- you can also include some CSS inline in your markup. However it is highly
|
||||||
recommended to avoid this. -->
|
recommended to avoid this. -->
|
||||||
<style>
|
<style>
|
||||||
a { color: purple; }
|
a { color: purple; }
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<!-- or directly set CSS properties on the element.
|
<!-- or directly set CSS properties on the element.
|
||||||
This has to be avoided as much as you can. -->
|
This has to be avoided as much as you can. -->
|
||||||
<div style="border: 1px solid red;">
|
<div style="border: 1px solid red;">
|
||||||
</div>
|
</div>
|
||||||
@ -186,8 +186,8 @@ This has to be avoided as much as you can. -->
|
|||||||
|
|
||||||
## Precedence
|
## Precedence
|
||||||
|
|
||||||
As you noticed an element may be targetted by more than one selector.
|
As you noticed an element may be targetted by more than one selector.
|
||||||
and may have a property set on it in more than one.
|
and may have a property set on it in more than one.
|
||||||
In these cases, one of the rules takes precedence over others.
|
In these cases, one of the rules takes precedence over others.
|
||||||
|
|
||||||
Given the following CSS:
|
Given the following CSS:
|
||||||
@ -217,24 +217,24 @@ and the following markup:
|
|||||||
</p>
|
</p>
|
||||||
```
|
```
|
||||||
|
|
||||||
The precedence of style is as followed:
|
The precedence of style is as followed:
|
||||||
Remember, the precedence is for each **property**, not for the entire block.
|
Remember, the precedence is for each **property**, not for the entire block.
|
||||||
|
|
||||||
* `E` has the highest precedence because of the keyword `!important`.
|
* `E` has the highest precedence because of the keyword `!important`.
|
||||||
It is recommended to avoid this unless it is strictly necessary to use.
|
It is recommended to avoid this unless it is strictly necessary to use.
|
||||||
* `F` is next, because it is inline style.
|
* `F` is next, because it is inline style.
|
||||||
* `A` is next, because it is more "specific" than anything else.
|
* `A` is next, because it is more "specific" than anything else.
|
||||||
more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
|
more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
|
||||||
class name `class1` + 1 attribute `attr='value'`
|
class name `class1` + 1 attribute `attr='value'`
|
||||||
* `C` is next. although it has the same specificness as `B`
|
* `C` is next. although it has the same specificness as `B`
|
||||||
but it appears last.
|
but it appears last.
|
||||||
* Then is `B`
|
* Then is `B`
|
||||||
* and lastly is `D`.
|
* and lastly is `D`.
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
|
|
||||||
Most of the features in CSS2 (and gradually in CSS3) are compatible across
|
Most of the features in CSS2 (and gradually in CSS3) are compatible across
|
||||||
all browsers and devices. But it's always vital to have in mind the compatibility
|
all browsers and devices. But it's always vital to have in mind the compatibility
|
||||||
of what you use in CSS with your target browsers.
|
of what you use in CSS with your target browsers.
|
||||||
|
|
||||||
[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
|
[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
language: D
|
language: D
|
||||||
filename: learnd.d
|
filename: learnd.d
|
||||||
contributors:
|
contributors:
|
||||||
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
|
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
|
||||||
lang: en
|
lang: en
|
||||||
@ -18,9 +18,9 @@ void main(string[] args) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If you're like me and spend way too much time on the internet, odds are you've heard
|
If you're like me and spend way too much time on the internet, odds are you've heard
|
||||||
about [D](http://dlang.org/). The D programming language is a modern, general-purpose,
|
about [D](http://dlang.org/). The D programming language is a modern, general-purpose,
|
||||||
multi-paradigm language with support for everything from low-level features to
|
multi-paradigm language with support for everything from low-level features to
|
||||||
expressive high-level abstractions.
|
expressive high-level abstractions.
|
||||||
|
|
||||||
D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
|
D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
|
||||||
@ -37,7 +37,7 @@ void main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
auto n = 1; // use auto for type inferred variables
|
auto n = 1; // use auto for type inferred variables
|
||||||
|
|
||||||
// Numeric literals can use _ as a digit seperator for clarity
|
// Numeric literals can use _ as a digit seperator for clarity
|
||||||
while(n < 10_000) {
|
while(n < 10_000) {
|
||||||
n += n;
|
n += n;
|
||||||
@ -49,7 +49,7 @@ void main() {
|
|||||||
|
|
||||||
// For and while are nice, but in D-land we prefer foreach
|
// For and while are nice, but in D-land we prefer foreach
|
||||||
// The .. creates a continuous range, excluding the end
|
// The .. creates a continuous range, excluding the end
|
||||||
foreach(i; 1..1_000_000) {
|
foreach(i; 1..1_000_000) {
|
||||||
if(n % 2 == 0)
|
if(n % 2 == 0)
|
||||||
writeln(i);
|
writeln(i);
|
||||||
}
|
}
|
||||||
@ -72,12 +72,12 @@ we can use templates to parameterize all of these on both types and values!
|
|||||||
// Here, T is a type parameter. Think <T> from C++/C#/Java
|
// Here, T is a type parameter. Think <T> from C++/C#/Java
|
||||||
struct LinkedList(T) {
|
struct LinkedList(T) {
|
||||||
T data = null;
|
T data = null;
|
||||||
LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
|
LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
|
||||||
}
|
}
|
||||||
|
|
||||||
class BinTree(T) {
|
class BinTree(T) {
|
||||||
T data = null;
|
T data = null;
|
||||||
|
|
||||||
// If there is only one template parameter, we can omit parens
|
// If there is only one template parameter, we can omit parens
|
||||||
BinTree!T left;
|
BinTree!T left;
|
||||||
BinTree!T right;
|
BinTree!T right;
|
||||||
@ -101,7 +101,7 @@ alias NumTree = BinTree!double;
|
|||||||
// We can create function templates as well!
|
// We can create function templates as well!
|
||||||
|
|
||||||
T max(T)(T a, T b) {
|
T max(T)(T a, T b) {
|
||||||
if(a < b)
|
if(a < b)
|
||||||
return b;
|
return b;
|
||||||
|
|
||||||
return a;
|
return a;
|
||||||
@ -114,7 +114,7 @@ void swap(T)(ref T a, ref T b) {
|
|||||||
auto temp = a;
|
auto temp = a;
|
||||||
|
|
||||||
a = b;
|
a = b;
|
||||||
b = temp;
|
b = temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// With templates, we can also parameterize on values, not just types
|
// With templates, we can also parameterize on values, not just types
|
||||||
@ -145,13 +145,13 @@ class MyClass(T, U) {
|
|||||||
class MyClass(T, U) {
|
class MyClass(T, U) {
|
||||||
T _data;
|
T _data;
|
||||||
U _other;
|
U _other;
|
||||||
|
|
||||||
// Constructors are always named `this`
|
// Constructors are always named `this`
|
||||||
this(T t, U u) {
|
this(T t, U u) {
|
||||||
data = t;
|
data = t;
|
||||||
other = u;
|
other = u;
|
||||||
}
|
}
|
||||||
|
|
||||||
// getters
|
// getters
|
||||||
@property T data() {
|
@property T data() {
|
||||||
return _data;
|
return _data;
|
||||||
@ -161,7 +161,7 @@ class MyClass(T, U) {
|
|||||||
return _other;
|
return _other;
|
||||||
}
|
}
|
||||||
|
|
||||||
// setters
|
// setters
|
||||||
@property void data(T t) {
|
@property void data(T t) {
|
||||||
_data = t;
|
_data = t;
|
||||||
}
|
}
|
||||||
@ -177,7 +177,7 @@ void main() {
|
|||||||
|
|
||||||
mc.data = 7;
|
mc.data = 7;
|
||||||
mc.other = "seven";
|
mc.other = "seven";
|
||||||
|
|
||||||
writeln(mc.data);
|
writeln(mc.data);
|
||||||
writeln(mc.other);
|
writeln(mc.other);
|
||||||
}
|
}
|
||||||
@ -193,7 +193,7 @@ and `override`ing methods. D does inheritance just like Java:
|
|||||||
Extend one class, implement as many interfaces as you please.
|
Extend one class, implement as many interfaces as you please.
|
||||||
|
|
||||||
We've seen D's OOP facilities, but let's switch gears. D offers
|
We've seen D's OOP facilities, but let's switch gears. D offers
|
||||||
functional programming with first-class functions, `pure`
|
functional programming with first-class functions, `pure`
|
||||||
functions, and immutable data. In addition, all of your favorite
|
functions, and immutable data. In addition, all of your favorite
|
||||||
functional algorithms (map, filter, reduce and friends) can be
|
functional algorithms (map, filter, reduce and friends) can be
|
||||||
found in the wonderful `std.algorithm` module!
|
found in the wonderful `std.algorithm` module!
|
||||||
@ -205,7 +205,7 @@ import std.range : iota; // builds an end-exclusive range
|
|||||||
void main() {
|
void main() {
|
||||||
// We want to print the sum of a list of squares of even ints
|
// We want to print the sum of a list of squares of even ints
|
||||||
// from 1 to 100. Easy!
|
// from 1 to 100. Easy!
|
||||||
|
|
||||||
// Just pass lambda expressions as template parameters!
|
// Just pass lambda expressions as template parameters!
|
||||||
// You can pass any old function you like, but lambdas are convenient here.
|
// You can pass any old function you like, but lambdas are convenient here.
|
||||||
auto num = iota(1, 101).filter!(x => x % 2 == 0)
|
auto num = iota(1, 101).filter!(x => x % 2 == 0)
|
||||||
@ -216,12 +216,12 @@ void main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Notice how we got to build a nice Haskellian pipeline to compute num?
|
Notice how we got to build a nice Haskellian pipeline to compute num?
|
||||||
That's thanks to a D innovation know as Uniform Function Call Syntax.
|
That's thanks to a D innovation know as Uniform Function Call Syntax.
|
||||||
With UFCS, we can choose whether to write a function call as a method
|
With UFCS, we can choose whether to write a function call as a method
|
||||||
or free function call! Walter wrote a nice article on this
|
or free function call! Walter wrote a nice article on this
|
||||||
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
||||||
In short, you can call functions whose first parameter
|
In short, you can call functions whose first parameter
|
||||||
is of some type A on any expression of type A as a method.
|
is of some type A on any expression of type A as a method.
|
||||||
|
|
||||||
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
|
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
|
||||||
|
@ -81,7 +81,7 @@ example5() {
|
|||||||
// Where classBody can include instance methods and variables, but also
|
// Where classBody can include instance methods and variables, but also
|
||||||
// class methods and variables.
|
// class methods and variables.
|
||||||
class Example6Class {
|
class Example6Class {
|
||||||
var example6InstanceVariable = "Example6 instance variable";
|
var example6InstanceVariable = "Example6 instance variable";
|
||||||
sayIt() {
|
sayIt() {
|
||||||
print(example6InstanceVariable);
|
print(example6InstanceVariable);
|
||||||
}
|
}
|
||||||
@ -92,7 +92,7 @@ example6() {
|
|||||||
|
|
||||||
// Class methods and variables are declared with "static" terms.
|
// Class methods and variables are declared with "static" terms.
|
||||||
class Example7Class {
|
class Example7Class {
|
||||||
static var example7ClassVariable = "Example7 class variable";
|
static var example7ClassVariable = "Example7 class variable";
|
||||||
static sayItFromClass() {
|
static sayItFromClass() {
|
||||||
print(example7ClassVariable);
|
print(example7ClassVariable);
|
||||||
}
|
}
|
||||||
@ -111,7 +111,7 @@ example7() {
|
|||||||
// by default. But arrays and maps are not. They can be made constant by
|
// by default. But arrays and maps are not. They can be made constant by
|
||||||
// declaring them "const".
|
// declaring them "const".
|
||||||
var example8A = const ["Example8 const array"],
|
var example8A = const ["Example8 const array"],
|
||||||
example8M = const {"someKey": "Example8 const map"};
|
example8M = const {"someKey": "Example8 const map"};
|
||||||
example8() {
|
example8() {
|
||||||
print(example8A[0]);
|
print(example8A[0]);
|
||||||
print(example8M["someKey"]);
|
print(example8M["someKey"]);
|
||||||
@ -245,7 +245,7 @@ example18() {
|
|||||||
// Strings with triple single-quotes or triple double-quotes span
|
// Strings with triple single-quotes or triple double-quotes span
|
||||||
// multiple lines and include line delimiters.
|
// multiple lines and include line delimiters.
|
||||||
example19() {
|
example19() {
|
||||||
print('''Example19 <a href="etc">
|
print('''Example19 <a href="etc">
|
||||||
Example19 Don't can't I'm Etc
|
Example19 Don't can't I'm Etc
|
||||||
Example19 </a>''');
|
Example19 </a>''');
|
||||||
}
|
}
|
||||||
@ -272,7 +272,7 @@ example20() {
|
|||||||
class Example21 {
|
class Example21 {
|
||||||
List<String> _names;
|
List<String> _names;
|
||||||
Example21() {
|
Example21() {
|
||||||
_names = ["a", "b"];
|
_names = ["a", "b"];
|
||||||
}
|
}
|
||||||
List<String> get names => _names;
|
List<String> get names => _names;
|
||||||
set names(List<String> list) {
|
set names(List<String> list) {
|
||||||
|
@ -292,7 +292,7 @@ calculateArea() ->
|
|||||||
_ ->
|
_ ->
|
||||||
io:format("We can only calculate area of rectangles or circles.")
|
io:format("We can only calculate area of rectangles or circles.")
|
||||||
end.
|
end.
|
||||||
|
|
||||||
% Compile the module and create a process that evaluates `calculateArea` in the
|
% Compile the module and create a process that evaluates `calculateArea` in the
|
||||||
% shell.
|
% shell.
|
||||||
c(calculateGeometry).
|
c(calculateGeometry).
|
||||||
|
@ -5,7 +5,7 @@ contributors:
|
|||||||
filename: learnfsharp.fs
|
filename: learnfsharp.fs
|
||||||
---
|
---
|
||||||
|
|
||||||
F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
|
F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
|
||||||
|
|
||||||
It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language.
|
It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language.
|
||||||
|
|
||||||
@ -90,7 +90,7 @@ let simplePatternMatch =
|
|||||||
| _ -> printfn "x is something else" // underscore matches anything
|
| _ -> printfn "x is something else" // underscore matches anything
|
||||||
|
|
||||||
// F# doesn't allow nulls by default -- you must use an Option type
|
// F# doesn't allow nulls by default -- you must use an Option type
|
||||||
// and then pattern match.
|
// and then pattern match.
|
||||||
// Some(..) and None are roughly analogous to Nullable wrappers
|
// Some(..) and None are roughly analogous to Nullable wrappers
|
||||||
let validValue = Some(99)
|
let validValue = Some(99)
|
||||||
let invalidValue = None
|
let invalidValue = None
|
||||||
@ -115,7 +115,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
|
|||||||
// into a string, similar to String.Format in C#.
|
// into a string, similar to String.Format in C#.
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// More on functions
|
// More on functions
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
// F# is a true functional language -- functions are first
|
// F# is a true functional language -- functions are first
|
||||||
@ -124,30 +124,30 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
|
|||||||
|
|
||||||
// Modules are used to group functions together
|
// Modules are used to group functions together
|
||||||
// Indentation is needed for each nested module.
|
// Indentation is needed for each nested module.
|
||||||
module FunctionExamples =
|
module FunctionExamples =
|
||||||
|
|
||||||
// define a simple adding function
|
// define a simple adding function
|
||||||
let add x y = x + y
|
let add x y = x + y
|
||||||
|
|
||||||
// basic usage of a function
|
// basic usage of a function
|
||||||
let a = add 1 2
|
let a = add 1 2
|
||||||
printfn "1+2 = %i" a
|
printfn "1+2 = %i" a
|
||||||
|
|
||||||
// partial application to "bake in" parameters
|
// partial application to "bake in" parameters
|
||||||
let add42 = add 42
|
let add42 = add 42
|
||||||
let b = add42 1
|
let b = add42 1
|
||||||
printfn "42+1 = %i" b
|
printfn "42+1 = %i" b
|
||||||
|
|
||||||
// composition to combine functions
|
// composition to combine functions
|
||||||
let add1 = add 1
|
let add1 = add 1
|
||||||
let add2 = add 2
|
let add2 = add 2
|
||||||
let add3 = add1 >> add2
|
let add3 = add1 >> add2
|
||||||
let c = add3 7
|
let c = add3 7
|
||||||
printfn "3+7 = %i" c
|
printfn "3+7 = %i" c
|
||||||
|
|
||||||
// higher order functions
|
// higher order functions
|
||||||
[1..10] |> List.map add3 |> printfn "new list is %A"
|
[1..10] |> List.map add3 |> printfn "new list is %A"
|
||||||
|
|
||||||
// lists of functions, and more
|
// lists of functions, and more
|
||||||
let add6 = [add1; add2; add3] |> List.reduce (>>)
|
let add6 = [add1; add2; add3] |> List.reduce (>>)
|
||||||
let d = add6 7
|
let d = add6 7
|
||||||
@ -158,54 +158,54 @@ module FunctionExamples =
|
|||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
// There are three types of ordered collection:
|
// There are three types of ordered collection:
|
||||||
// * Lists are most basic immutable collection.
|
// * Lists are most basic immutable collection.
|
||||||
// * Arrays are mutable and more efficient when needed.
|
// * Arrays are mutable and more efficient when needed.
|
||||||
// * Sequences are lazy and infinite (e.g. an enumerator).
|
// * Sequences are lazy and infinite (e.g. an enumerator).
|
||||||
//
|
//
|
||||||
// Other collections include immutable maps and sets
|
// Other collections include immutable maps and sets
|
||||||
// plus all the standard .NET collections
|
// plus all the standard .NET collections
|
||||||
|
|
||||||
module ListExamples =
|
module ListExamples =
|
||||||
|
|
||||||
// lists use square brackets
|
// lists use square brackets
|
||||||
let list1 = ["a";"b"]
|
let list1 = ["a";"b"]
|
||||||
let list2 = "c" :: list1 // :: is prepending
|
let list2 = "c" :: list1 // :: is prepending
|
||||||
let list3 = list1 @ list2 // @ is concat
|
let list3 = list1 @ list2 // @ is concat
|
||||||
|
|
||||||
// list comprehensions (aka generators)
|
// list comprehensions (aka generators)
|
||||||
let squares = [for i in 1..10 do yield i*i]
|
let squares = [for i in 1..10 do yield i*i]
|
||||||
|
|
||||||
// prime number generator
|
// prime number generator
|
||||||
let rec sieve = function
|
let rec sieve = function
|
||||||
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
|
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
|
||||||
| [] -> []
|
| [] -> []
|
||||||
let primes = sieve [2..50]
|
let primes = sieve [2..50]
|
||||||
printfn "%A" primes
|
printfn "%A" primes
|
||||||
|
|
||||||
// pattern matching for lists
|
// pattern matching for lists
|
||||||
let listMatcher aList =
|
let listMatcher aList =
|
||||||
match aList with
|
match aList with
|
||||||
| [] -> printfn "the list is empty"
|
| [] -> printfn "the list is empty"
|
||||||
| [first] -> printfn "the list has one element %A " first
|
| [first] -> printfn "the list has one element %A " first
|
||||||
| [first; second] -> printfn "list is %A and %A" first second
|
| [first; second] -> printfn "list is %A and %A" first second
|
||||||
| _ -> printfn "the list has more than two elements"
|
| _ -> printfn "the list has more than two elements"
|
||||||
|
|
||||||
listMatcher [1;2;3;4]
|
listMatcher [1;2;3;4]
|
||||||
listMatcher [1;2]
|
listMatcher [1;2]
|
||||||
listMatcher [1]
|
listMatcher [1]
|
||||||
listMatcher []
|
listMatcher []
|
||||||
|
|
||||||
// recursion using lists
|
// recursion using lists
|
||||||
let rec sum aList =
|
let rec sum aList =
|
||||||
match aList with
|
match aList with
|
||||||
| [] -> 0
|
| [] -> 0
|
||||||
| x::xs -> x + sum xs
|
| x::xs -> x + sum xs
|
||||||
sum [1..10]
|
sum [1..10]
|
||||||
|
|
||||||
// -----------------------------------------
|
|
||||||
// Standard library functions
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Standard library functions
|
||||||
|
// -----------------------------------------
|
||||||
|
|
||||||
// map
|
// map
|
||||||
let add3 x = x + 3
|
let add3 x = x + 3
|
||||||
[1..10] |> List.map add3
|
[1..10] |> List.map add3
|
||||||
@ -213,68 +213,68 @@ module ListExamples =
|
|||||||
// filter
|
// filter
|
||||||
let even x = x % 2 = 0
|
let even x = x % 2 = 0
|
||||||
[1..10] |> List.filter even
|
[1..10] |> List.filter even
|
||||||
|
|
||||||
// many more -- see documentation
|
// many more -- see documentation
|
||||||
|
|
||||||
module ArrayExamples =
|
module ArrayExamples =
|
||||||
|
|
||||||
// arrays use square brackets with bar
|
// arrays use square brackets with bar
|
||||||
let array1 = [| "a";"b" |]
|
let array1 = [| "a";"b" |]
|
||||||
let first = array1.[0] // indexed access using dot
|
let first = array1.[0] // indexed access using dot
|
||||||
|
|
||||||
// pattern matching for arrays is same as for lists
|
// pattern matching for arrays is same as for lists
|
||||||
let arrayMatcher aList =
|
let arrayMatcher aList =
|
||||||
match aList with
|
match aList with
|
||||||
| [| |] -> printfn "the array is empty"
|
| [| |] -> printfn "the array is empty"
|
||||||
| [| first |] -> printfn "the array has one element %A " first
|
| [| first |] -> printfn "the array has one element %A " first
|
||||||
| [| first; second |] -> printfn "array is %A and %A" first second
|
| [| first; second |] -> printfn "array is %A and %A" first second
|
||||||
| _ -> printfn "the array has more than two elements"
|
| _ -> printfn "the array has more than two elements"
|
||||||
|
|
||||||
arrayMatcher [| 1;2;3;4 |]
|
arrayMatcher [| 1;2;3;4 |]
|
||||||
|
|
||||||
// Standard library functions just as for List
|
// Standard library functions just as for List
|
||||||
|
|
||||||
[| 1..10 |]
|
[| 1..10 |]
|
||||||
|> Array.map (fun i -> i+3)
|
|> Array.map (fun i -> i+3)
|
||||||
|> Array.filter (fun i -> i%2 = 0)
|
|> Array.filter (fun i -> i%2 = 0)
|
||||||
|> Array.iter (printfn "value is %i. ")
|
|> Array.iter (printfn "value is %i. ")
|
||||||
|
|
||||||
|
|
||||||
module SequenceExamples =
|
module SequenceExamples =
|
||||||
|
|
||||||
// sequences use curly braces
|
// sequences use curly braces
|
||||||
let seq1 = seq { yield "a"; yield "b" }
|
let seq1 = seq { yield "a"; yield "b" }
|
||||||
|
|
||||||
// sequences can use yield and
|
// sequences can use yield and
|
||||||
// can contain subsequences
|
// can contain subsequences
|
||||||
let strange = seq {
|
let strange = seq {
|
||||||
// "yield! adds one element
|
// "yield! adds one element
|
||||||
yield 1; yield 2;
|
yield 1; yield 2;
|
||||||
|
|
||||||
// "yield!" adds a whole subsequence
|
// "yield!" adds a whole subsequence
|
||||||
yield! [5..10]
|
yield! [5..10]
|
||||||
yield! seq {
|
yield! seq {
|
||||||
for i in 1..10 do
|
for i in 1..10 do
|
||||||
if i%2 = 0 then yield i }}
|
if i%2 = 0 then yield i }}
|
||||||
// test
|
// test
|
||||||
strange |> Seq.toList
|
strange |> Seq.toList
|
||||||
|
|
||||||
|
|
||||||
// Sequences can be created using "unfold"
|
// Sequences can be created using "unfold"
|
||||||
// Here's the fibonacci series
|
// Here's the fibonacci series
|
||||||
let fib = Seq.unfold (fun (fst,snd) ->
|
let fib = Seq.unfold (fun (fst,snd) ->
|
||||||
Some(fst + snd, (snd, fst + snd))) (0,1)
|
Some(fst + snd, (snd, fst + snd))) (0,1)
|
||||||
|
|
||||||
// test
|
// test
|
||||||
let fib10 = fib |> Seq.take 10 |> Seq.toList
|
let fib10 = fib |> Seq.take 10 |> Seq.toList
|
||||||
printf "first 10 fibs are %A" fib10
|
printf "first 10 fibs are %A" fib10
|
||||||
|
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Data Types
|
// Data Types
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module DataTypeExamples =
|
module DataTypeExamples =
|
||||||
|
|
||||||
// All data is immutable by default
|
// All data is immutable by default
|
||||||
|
|
||||||
@ -282,33 +282,33 @@ module DataTypeExamples =
|
|||||||
// -- Use a comma to create a tuple
|
// -- Use a comma to create a tuple
|
||||||
let twoTuple = 1,2
|
let twoTuple = 1,2
|
||||||
let threeTuple = "a",2,true
|
let threeTuple = "a",2,true
|
||||||
|
|
||||||
// Pattern match to unpack
|
// Pattern match to unpack
|
||||||
let x,y = twoTuple //sets x=1 y=2
|
let x,y = twoTuple //sets x=1 y=2
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Record types have named fields
|
// Record types have named fields
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Use "type" with curly braces to define a record type
|
// Use "type" with curly braces to define a record type
|
||||||
type Person = {First:string; Last:string}
|
type Person = {First:string; Last:string}
|
||||||
|
|
||||||
// Use "let" with curly braces to create a record
|
// Use "let" with curly braces to create a record
|
||||||
let person1 = {First="John"; Last="Doe"}
|
let person1 = {First="John"; Last="Doe"}
|
||||||
|
|
||||||
// Pattern match to unpack
|
// Pattern match to unpack
|
||||||
let {First=first} = person1 //sets first="john"
|
let {First=first} = person1 //sets first="john"
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Union types (aka variants) have a set of choices
|
// Union types (aka variants) have a set of choices
|
||||||
// Only case can be valid at a time.
|
// Only case can be valid at a time.
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Use "type" with bar/pipe to define a union type
|
// Use "type" with bar/pipe to define a union type
|
||||||
type Temp =
|
type Temp =
|
||||||
| DegreesC of float
|
| DegreesC of float
|
||||||
| DegreesF of float
|
| DegreesF of float
|
||||||
|
|
||||||
// Use one of the cases to create one
|
// Use one of the cases to create one
|
||||||
let temp1 = DegreesF 98.6
|
let temp1 = DegreesF 98.6
|
||||||
let temp2 = DegreesC 37.0
|
let temp2 = DegreesC 37.0
|
||||||
@ -317,29 +317,29 @@ module DataTypeExamples =
|
|||||||
let printTemp = function
|
let printTemp = function
|
||||||
| DegreesC t -> printfn "%f degC" t
|
| DegreesC t -> printfn "%f degC" t
|
||||||
| DegreesF t -> printfn "%f degF" t
|
| DegreesF t -> printfn "%f degF" t
|
||||||
|
|
||||||
printTemp temp1
|
printTemp temp1
|
||||||
printTemp temp2
|
printTemp temp2
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Recursive types
|
// Recursive types
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Types can be combined recursively in complex ways
|
// Types can be combined recursively in complex ways
|
||||||
// without having to create subclasses
|
// without having to create subclasses
|
||||||
type Employee =
|
type Employee =
|
||||||
| Worker of Person
|
| Worker of Person
|
||||||
| Manager of Employee list
|
| Manager of Employee list
|
||||||
|
|
||||||
let jdoe = {First="John";Last="Doe"}
|
let jdoe = {First="John";Last="Doe"}
|
||||||
let worker = Worker jdoe
|
let worker = Worker jdoe
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Modelling with types
|
// Modelling with types
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Union types are great for modelling state without using flags
|
// Union types are great for modelling state without using flags
|
||||||
type EmailAddress =
|
type EmailAddress =
|
||||||
| ValidEmailAddress of string
|
| ValidEmailAddress of string
|
||||||
| InvalidEmailAddress of string
|
| InvalidEmailAddress of string
|
||||||
|
|
||||||
@ -350,40 +350,40 @@ module DataTypeExamples =
|
|||||||
|
|
||||||
// The combination of union types and record types together
|
// The combination of union types and record types together
|
||||||
// provide a great foundation for domain driven design.
|
// provide a great foundation for domain driven design.
|
||||||
// You can create hundreds of little types that accurately
|
// You can create hundreds of little types that accurately
|
||||||
// reflect the domain.
|
// reflect the domain.
|
||||||
|
|
||||||
type CartItem = { ProductCode: string; Qty: int }
|
type CartItem = { ProductCode: string; Qty: int }
|
||||||
type Payment = Payment of float
|
type Payment = Payment of float
|
||||||
type ActiveCartData = { UnpaidItems: CartItem list }
|
type ActiveCartData = { UnpaidItems: CartItem list }
|
||||||
type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
|
type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
|
||||||
|
|
||||||
type ShoppingCart =
|
type ShoppingCart =
|
||||||
| EmptyCart // no data
|
| EmptyCart // no data
|
||||||
| ActiveCart of ActiveCartData
|
| ActiveCart of ActiveCartData
|
||||||
| PaidCart of PaidCartData
|
| PaidCart of PaidCartData
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Built in behavior for types
|
// Built in behavior for types
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Core types have useful "out-of-the-box" behavior, no coding needed.
|
// Core types have useful "out-of-the-box" behavior, no coding needed.
|
||||||
// * Immutability
|
// * Immutability
|
||||||
// * Pretty printing when debugging
|
// * Pretty printing when debugging
|
||||||
// * Equality and comparison
|
// * Equality and comparison
|
||||||
// * Serialization
|
// * Serialization
|
||||||
|
|
||||||
// Pretty printing using %A
|
// Pretty printing using %A
|
||||||
printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
|
printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
|
||||||
twoTuple person1 temp1 worker
|
twoTuple person1 temp1 worker
|
||||||
|
|
||||||
// Equality and comparison built in.
|
// Equality and comparison built in.
|
||||||
// Here's an example with cards.
|
// Here's an example with cards.
|
||||||
type Suit = Club | Diamond | Spade | Heart
|
type Suit = Club | Diamond | Spade | Heart
|
||||||
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
||||||
| Nine | Ten | Jack | Queen | King | Ace
|
| Nine | Ten | Jack | Queen | King | Ace
|
||||||
|
|
||||||
let hand = [ Club,Ace; Heart,Three; Heart,Ace;
|
let hand = [ Club,Ace; Heart,Three; Heart,Ace;
|
||||||
Spade,Jack; Diamond,Two; Diamond,Ace ]
|
Spade,Jack; Diamond,Two; Diamond,Ace ]
|
||||||
|
|
||||||
// sorting
|
// sorting
|
||||||
@ -391,27 +391,27 @@ module DataTypeExamples =
|
|||||||
List.max hand |> printfn "high card is %A"
|
List.max hand |> printfn "high card is %A"
|
||||||
List.min hand |> printfn "low card is %A"
|
List.min hand |> printfn "low card is %A"
|
||||||
|
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Active patterns
|
// Active patterns
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module ActivePatternExamples =
|
module ActivePatternExamples =
|
||||||
|
|
||||||
// F# has a special type of pattern matching called "active patterns"
|
// F# has a special type of pattern matching called "active patterns"
|
||||||
// where the pattern can be parsed or detected dynamically.
|
// where the pattern can be parsed or detected dynamically.
|
||||||
|
|
||||||
// "banana clips" are the syntax for active patterns
|
// "banana clips" are the syntax for active patterns
|
||||||
|
|
||||||
// for example, define an "active" pattern to match character types...
|
// for example, define an "active" pattern to match character types...
|
||||||
let (|Digit|Letter|Whitespace|Other|) ch =
|
let (|Digit|Letter|Whitespace|Other|) ch =
|
||||||
if System.Char.IsDigit(ch) then Digit
|
if System.Char.IsDigit(ch) then Digit
|
||||||
else if System.Char.IsLetter(ch) then Letter
|
else if System.Char.IsLetter(ch) then Letter
|
||||||
else if System.Char.IsWhiteSpace(ch) then Whitespace
|
else if System.Char.IsWhiteSpace(ch) then Whitespace
|
||||||
else Other
|
else Other
|
||||||
|
|
||||||
// ... and then use it to make parsing logic much clearer
|
// ... and then use it to make parsing logic much clearer
|
||||||
let printChar ch =
|
let printChar ch =
|
||||||
match ch with
|
match ch with
|
||||||
| Digit -> printfn "%c is a Digit" ch
|
| Digit -> printfn "%c is a Digit" ch
|
||||||
| Letter -> printfn "%c is a Letter" ch
|
| Letter -> printfn "%c is a Letter" ch
|
||||||
@ -424,52 +424,52 @@ module ActivePatternExamples =
|
|||||||
// -----------------------------------
|
// -----------------------------------
|
||||||
// FizzBuzz using active patterns
|
// FizzBuzz using active patterns
|
||||||
// -----------------------------------
|
// -----------------------------------
|
||||||
|
|
||||||
// You can create partial matching patterns as well
|
// You can create partial matching patterns as well
|
||||||
// Just use undercore in the defintion, and return Some if matched.
|
// Just use undercore in the defintion, and return Some if matched.
|
||||||
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
|
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
|
||||||
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
|
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
|
||||||
|
|
||||||
// the main function
|
// the main function
|
||||||
let fizzBuzz i =
|
let fizzBuzz i =
|
||||||
match i with
|
match i with
|
||||||
| MultOf3 & MultOf5 -> printf "FizzBuzz, "
|
| MultOf3 & MultOf5 -> printf "FizzBuzz, "
|
||||||
| MultOf3 -> printf "Fizz, "
|
| MultOf3 -> printf "Fizz, "
|
||||||
| MultOf5 -> printf "Buzz, "
|
| MultOf5 -> printf "Buzz, "
|
||||||
| _ -> printf "%i, " i
|
| _ -> printf "%i, " i
|
||||||
|
|
||||||
// test
|
// test
|
||||||
[1..20] |> List.iter fizzBuzz
|
[1..20] |> List.iter fizzBuzz
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Conciseness
|
// Conciseness
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module AlgorithmExamples =
|
module AlgorithmExamples =
|
||||||
|
|
||||||
// F# has a high signal/noise ratio, so code reads
|
// F# has a high signal/noise ratio, so code reads
|
||||||
// almost like the actual algorithm
|
// almost like the actual algorithm
|
||||||
|
|
||||||
// ------ Example: define sumOfSquares function ------
|
// ------ Example: define sumOfSquares function ------
|
||||||
let sumOfSquares n =
|
let sumOfSquares n =
|
||||||
[1..n] // 1) take all the numbers from 1 to n
|
[1..n] // 1) take all the numbers from 1 to n
|
||||||
|> List.map square // 2) square each one
|
|> List.map square // 2) square each one
|
||||||
|> List.sum // 3) sum the results
|
|> List.sum // 3) sum the results
|
||||||
|
|
||||||
// test
|
// test
|
||||||
sumOfSquares 100 |> printfn "Sum of squares = %A"
|
sumOfSquares 100 |> printfn "Sum of squares = %A"
|
||||||
|
|
||||||
// ------ Example: define a sort function ------
|
// ------ Example: define a sort function ------
|
||||||
let rec sort list =
|
let rec sort list =
|
||||||
match list with
|
match list with
|
||||||
// If the list is empty
|
// If the list is empty
|
||||||
| [] ->
|
| [] ->
|
||||||
[] // return an empty list
|
[] // return an empty list
|
||||||
// If the list is not empty
|
// If the list is not empty
|
||||||
| firstElem::otherElements -> // take the first element
|
| firstElem::otherElements -> // take the first element
|
||||||
let smallerElements = // extract the smaller elements
|
let smallerElements = // extract the smaller elements
|
||||||
otherElements // from the remaining ones
|
otherElements // from the remaining ones
|
||||||
|> List.filter (fun e -> e < firstElem)
|
|> List.filter (fun e -> e < firstElem)
|
||||||
|> sort // and sort them
|
|> sort // and sort them
|
||||||
let largerElements = // extract the larger ones
|
let largerElements = // extract the larger ones
|
||||||
otherElements // from the remaining ones
|
otherElements // from the remaining ones
|
||||||
@ -479,13 +479,13 @@ module AlgorithmExamples =
|
|||||||
List.concat [smallerElements; [firstElem]; largerElements]
|
List.concat [smallerElements; [firstElem]; largerElements]
|
||||||
|
|
||||||
// test
|
// test
|
||||||
sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
|
sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Asynchronous Code
|
// Asynchronous Code
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module AsyncExample =
|
module AsyncExample =
|
||||||
|
|
||||||
// F# has built-in features to help with async code
|
// F# has built-in features to help with async code
|
||||||
// without encountering the "pyramid of doom"
|
// without encountering the "pyramid of doom"
|
||||||
@ -495,23 +495,23 @@ module AsyncExample =
|
|||||||
open System.Net
|
open System.Net
|
||||||
open System
|
open System
|
||||||
open System.IO
|
open System.IO
|
||||||
open Microsoft.FSharp.Control.CommonExtensions
|
open Microsoft.FSharp.Control.CommonExtensions
|
||||||
|
|
||||||
// Fetch the contents of a URL asynchronously
|
// Fetch the contents of a URL asynchronously
|
||||||
let fetchUrlAsync url =
|
let fetchUrlAsync url =
|
||||||
async { // "async" keyword and curly braces
|
async { // "async" keyword and curly braces
|
||||||
// creates an "async" object
|
// creates an "async" object
|
||||||
let req = WebRequest.Create(Uri(url))
|
let req = WebRequest.Create(Uri(url))
|
||||||
use! resp = req.AsyncGetResponse()
|
use! resp = req.AsyncGetResponse()
|
||||||
// use! is async assignment
|
// use! is async assignment
|
||||||
use stream = resp.GetResponseStream()
|
use stream = resp.GetResponseStream()
|
||||||
// "use" triggers automatic close()
|
// "use" triggers automatic close()
|
||||||
// on resource at end of scope
|
// on resource at end of scope
|
||||||
use reader = new IO.StreamReader(stream)
|
use reader = new IO.StreamReader(stream)
|
||||||
let html = reader.ReadToEnd()
|
let html = reader.ReadToEnd()
|
||||||
printfn "finished downloading %s" url
|
printfn "finished downloading %s" url
|
||||||
}
|
}
|
||||||
|
|
||||||
// a list of sites to fetch
|
// a list of sites to fetch
|
||||||
let sites = ["http://www.bing.com";
|
let sites = ["http://www.bing.com";
|
||||||
"http://www.google.com";
|
"http://www.google.com";
|
||||||
@ -520,7 +520,7 @@ module AsyncExample =
|
|||||||
"http://www.yahoo.com"]
|
"http://www.yahoo.com"]
|
||||||
|
|
||||||
// do it
|
// do it
|
||||||
sites
|
sites
|
||||||
|> List.map fetchUrlAsync // make a list of async tasks
|
|> List.map fetchUrlAsync // make a list of async tasks
|
||||||
|> Async.Parallel // set up the tasks to run in parallel
|
|> Async.Parallel // set up the tasks to run in parallel
|
||||||
|> Async.RunSynchronously // start them off
|
|> Async.RunSynchronously // start them off
|
||||||
@ -529,58 +529,58 @@ module AsyncExample =
|
|||||||
// .NET compatability
|
// .NET compatability
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module NetCompatibilityExamples =
|
module NetCompatibilityExamples =
|
||||||
|
|
||||||
// F# can do almost everything C# can do, and it integrates
|
// F# can do almost everything C# can do, and it integrates
|
||||||
// seamlessly with .NET or Mono libraries.
|
// seamlessly with .NET or Mono libraries.
|
||||||
|
|
||||||
// ------- work with existing library functions -------
|
// ------- work with existing library functions -------
|
||||||
|
|
||||||
let (i1success,i1) = System.Int32.TryParse("123");
|
let (i1success,i1) = System.Int32.TryParse("123");
|
||||||
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
|
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
|
||||||
|
|
||||||
// ------- Implement interfaces on the fly! -------
|
// ------- Implement interfaces on the fly! -------
|
||||||
|
|
||||||
// create a new object that implements IDisposable
|
// create a new object that implements IDisposable
|
||||||
let makeResource name =
|
let makeResource name =
|
||||||
{ new System.IDisposable
|
{ new System.IDisposable
|
||||||
with member this.Dispose() = printfn "%s disposed" name }
|
with member this.Dispose() = printfn "%s disposed" name }
|
||||||
|
|
||||||
let useAndDisposeResources =
|
let useAndDisposeResources =
|
||||||
use r1 = makeResource "first resource"
|
use r1 = makeResource "first resource"
|
||||||
printfn "using first resource"
|
printfn "using first resource"
|
||||||
for i in [1..3] do
|
for i in [1..3] do
|
||||||
let resourceName = sprintf "\tinner resource %d" i
|
let resourceName = sprintf "\tinner resource %d" i
|
||||||
use temp = makeResource resourceName
|
use temp = makeResource resourceName
|
||||||
printfn "\tdo something with %s" resourceName
|
printfn "\tdo something with %s" resourceName
|
||||||
use r2 = makeResource "second resource"
|
use r2 = makeResource "second resource"
|
||||||
printfn "using second resource"
|
printfn "using second resource"
|
||||||
printfn "done."
|
printfn "done."
|
||||||
|
|
||||||
// ------- Object oriented code -------
|
// ------- Object oriented code -------
|
||||||
|
|
||||||
// F# is also a fully fledged OO language.
|
// F# is also a fully fledged OO language.
|
||||||
// It supports classes, inheritance, virtual methods, etc.
|
// It supports classes, inheritance, virtual methods, etc.
|
||||||
|
|
||||||
// interface with generic type
|
// interface with generic type
|
||||||
type IEnumerator<'a> =
|
type IEnumerator<'a> =
|
||||||
abstract member Current : 'a
|
abstract member Current : 'a
|
||||||
abstract MoveNext : unit -> bool
|
abstract MoveNext : unit -> bool
|
||||||
|
|
||||||
// abstract base class with virtual methods
|
// abstract base class with virtual methods
|
||||||
[<AbstractClass>]
|
[<AbstractClass>]
|
||||||
type Shape() =
|
type Shape() =
|
||||||
//readonly properties
|
//readonly properties
|
||||||
abstract member Width : int with get
|
abstract member Width : int with get
|
||||||
abstract member Height : int with get
|
abstract member Height : int with get
|
||||||
//non-virtual method
|
//non-virtual method
|
||||||
member this.BoundingArea = this.Height * this.Width
|
member this.BoundingArea = this.Height * this.Width
|
||||||
//virtual method with base implementation
|
//virtual method with base implementation
|
||||||
abstract member Print : unit -> unit
|
abstract member Print : unit -> unit
|
||||||
default this.Print () = printfn "I'm a shape"
|
default this.Print () = printfn "I'm a shape"
|
||||||
|
|
||||||
// concrete class that inherits from base class and overrides
|
// concrete class that inherits from base class and overrides
|
||||||
type Rectangle(x:int, y:int) =
|
type Rectangle(x:int, y:int) =
|
||||||
inherit Shape()
|
inherit Shape()
|
||||||
override this.Width = x
|
override this.Width = x
|
||||||
override this.Height = y
|
override this.Height = y
|
||||||
@ -590,20 +590,20 @@ module NetCompatibilityExamples =
|
|||||||
let r = Rectangle(2,3)
|
let r = Rectangle(2,3)
|
||||||
printfn "The width is %i" r.Width
|
printfn "The width is %i" r.Width
|
||||||
printfn "The area is %i" r.BoundingArea
|
printfn "The area is %i" r.BoundingArea
|
||||||
r.Print()
|
r.Print()
|
||||||
|
|
||||||
// ------- extension methods -------
|
// ------- extension methods -------
|
||||||
|
|
||||||
//Just as in C#, F# can extend existing classes with extension methods.
|
//Just as in C#, F# can extend existing classes with extension methods.
|
||||||
type System.String with
|
type System.String with
|
||||||
member this.StartsWithA = this.StartsWith "A"
|
member this.StartsWithA = this.StartsWith "A"
|
||||||
|
|
||||||
//test
|
//test
|
||||||
let s = "Alice"
|
let s = "Alice"
|
||||||
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
||||||
|
|
||||||
// ------- events -------
|
// ------- events -------
|
||||||
|
|
||||||
type MyButton() =
|
type MyButton() =
|
||||||
let clickEvent = new Event<_>()
|
let clickEvent = new Event<_>()
|
||||||
|
|
||||||
@ -615,11 +615,11 @@ module NetCompatibilityExamples =
|
|||||||
|
|
||||||
// test
|
// test
|
||||||
let myButton = new MyButton()
|
let myButton = new MyButton()
|
||||||
myButton.OnClick.Add(fun (sender, arg) ->
|
myButton.OnClick.Add(fun (sender, arg) ->
|
||||||
printfn "Click event with arg=%O" arg)
|
printfn "Click event with arg=%O" arg)
|
||||||
|
|
||||||
myButton.TestEvent("Hello World!")
|
myButton.TestEvent("Hello World!")
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## More Information
|
## More Information
|
||||||
|
@ -51,7 +51,7 @@ function identity(?string $stringOrNull) : ?string
|
|||||||
class TypeHintedProperties
|
class TypeHintedProperties
|
||||||
{
|
{
|
||||||
public ?string $name;
|
public ?string $name;
|
||||||
|
|
||||||
protected int $id;
|
protected int $id;
|
||||||
|
|
||||||
private float $score = 100.0;
|
private float $score = 100.0;
|
||||||
@ -91,7 +91,7 @@ function openBox(Box<int> $box) : int
|
|||||||
|
|
||||||
|
|
||||||
// Shapes
|
// Shapes
|
||||||
//
|
//
|
||||||
// Hack adds the concept of shapes for defining struct-like arrays with a
|
// Hack adds the concept of shapes for defining struct-like arrays with a
|
||||||
// guaranteed, type-checked set of keys
|
// guaranteed, type-checked set of keys
|
||||||
type Point2D = shape('x' => int, 'y' => int);
|
type Point2D = shape('x' => int, 'y' => int);
|
||||||
@ -108,7 +108,7 @@ distance(
|
|||||||
|
|
||||||
|
|
||||||
// Type aliasing
|
// Type aliasing
|
||||||
//
|
//
|
||||||
// Hack adds a bunch of type aliasing features for making complex types readable
|
// Hack adds a bunch of type aliasing features for making complex types readable
|
||||||
newtype VectorArray = array<int, Vector<int>>;
|
newtype VectorArray = array<int, Vector<int>>;
|
||||||
|
|
||||||
@ -142,7 +142,7 @@ function getRoadType() : RoadType
|
|||||||
|
|
||||||
|
|
||||||
// Constructor argument promotion
|
// Constructor argument promotion
|
||||||
//
|
//
|
||||||
// To avoid boilerplate property and constructor definitions that only set
|
// To avoid boilerplate property and constructor definitions that only set
|
||||||
// properties, Hack adds a concise syntax for defining properties and a
|
// properties, Hack adds a concise syntax for defining properties and a
|
||||||
// constructor at the same time.
|
// constructor at the same time.
|
||||||
@ -171,12 +171,12 @@ class WithoutArgumentPromotion
|
|||||||
|
|
||||||
|
|
||||||
// Co-operative multi-tasking
|
// Co-operative multi-tasking
|
||||||
//
|
//
|
||||||
// Two new keywords "async" and "await" can be used to perform multi-tasking
|
// Two new keywords "async" and "await" can be used to perform multi-tasking
|
||||||
// Note that this does not involve threads - it just allows transfer of control
|
// Note that this does not involve threads - it just allows transfer of control
|
||||||
async function cooperativePrint(int $start, int $end) : Awaitable<void>
|
async function cooperativePrint(int $start, int $end) : Awaitable<void>
|
||||||
{
|
{
|
||||||
for ($i = $start; $i <= $end; $i++) {
|
for ($i = $start; $i <= $end; $i++) {
|
||||||
echo "$i ";
|
echo "$i ";
|
||||||
|
|
||||||
// Give other tasks a chance to do something
|
// Give other tasks a chance to do something
|
||||||
@ -193,9 +193,9 @@ AwaitAllWaitHandle::fromArray([
|
|||||||
|
|
||||||
|
|
||||||
// Attributes
|
// Attributes
|
||||||
//
|
//
|
||||||
// Attributes are a form of metadata for functions. Hack provides some
|
// Attributes are a form of metadata for functions. Hack provides some
|
||||||
// special built-in attributes that introduce useful behaviour.
|
// special built-in attributes that introduce useful behaviour.
|
||||||
|
|
||||||
// The __Memoize special attribute causes the result of a function to be cached
|
// The __Memoize special attribute causes the result of a function to be cached
|
||||||
<<__Memoize>>
|
<<__Memoize>>
|
||||||
@ -248,7 +248,7 @@ class ConsistentBar extends ConsistentFoo
|
|||||||
class InvalidFooSubclass extends ConsistentFoo
|
class InvalidFooSubclass extends ConsistentFoo
|
||||||
{
|
{
|
||||||
// Not matching the parent constructor will cause a type checker error:
|
// Not matching the parent constructor will cause a type checker error:
|
||||||
//
|
//
|
||||||
// "This object is of type ConsistentBaz. It is incompatible with this object
|
// "This object is of type ConsistentBaz. It is incompatible with this object
|
||||||
// of type ConsistentFoo because some of their methods are incompatible"
|
// of type ConsistentFoo because some of their methods are incompatible"
|
||||||
//
|
//
|
||||||
@ -259,7 +259,7 @@ class InvalidFooSubclass extends ConsistentFoo
|
|||||||
|
|
||||||
// Using the __Override annotation on a non-overriden method will cause a
|
// Using the __Override annotation on a non-overriden method will cause a
|
||||||
// type checker error:
|
// type checker error:
|
||||||
//
|
//
|
||||||
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
|
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
|
||||||
// parent definition found or overridden parent is defined in non-<?hh code"
|
// parent definition found or overridden parent is defined in non-<?hh code"
|
||||||
//
|
//
|
||||||
|
@ -62,11 +62,11 @@ $ haml input_file.haml output_file.html
|
|||||||
%h1 Headline copy
|
%h1 Headline copy
|
||||||
|
|
||||||
/ To write multiline content, nest it instead
|
/ To write multiline content, nest it instead
|
||||||
%p
|
%p
|
||||||
This is a lot of content that we could probably split onto two
|
This is a lot of content that we could probably split onto two
|
||||||
separate lines.
|
separate lines.
|
||||||
|
|
||||||
/
|
/
|
||||||
You can escape html by using the ampersand and equals sign ( &= ). This
|
You can escape html by using the ampersand and equals sign ( &= ). This
|
||||||
converts html-sensitive characters (&, /, :) into their html encoded
|
converts html-sensitive characters (&, /, :) into their html encoded
|
||||||
equivalents. For example
|
equivalents. For example
|
||||||
@ -102,7 +102,7 @@ $ haml input_file.haml output_file.html
|
|||||||
/ Inserting Ruby
|
/ Inserting Ruby
|
||||||
/ -------------------------------------------
|
/ -------------------------------------------
|
||||||
|
|
||||||
/
|
/
|
||||||
To output a Ruby value as the contents of a tag, use an equals sign followed
|
To output a Ruby value as the contents of a tag, use an equals sign followed
|
||||||
by the Ruby code
|
by the Ruby code
|
||||||
|
|
||||||
@ -141,7 +141,7 @@ $ haml input_file.haml output_file.html
|
|||||||
/ -------------------------------------------
|
/ -------------------------------------------
|
||||||
|
|
||||||
/
|
/
|
||||||
Use the colon to define Haml filters, one example of a filter you can
|
Use the colon to define Haml filters, one example of a filter you can
|
||||||
use is :javascript, which can be used for writing inline js
|
use is :javascript, which can be used for writing inline js
|
||||||
|
|
||||||
:javascript
|
:javascript
|
||||||
|
@ -47,9 +47,9 @@ public class LearnJava {
|
|||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Variables
|
// Variables
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Variable Declaration
|
* Variable Declaration
|
||||||
*/
|
*/
|
||||||
@ -325,29 +325,29 @@ public class LearnJava {
|
|||||||
|
|
||||||
// toString returns this Object's string representation.
|
// toString returns this Object's string representation.
|
||||||
System.out.println("trek info: " + trek.toString());
|
System.out.println("trek info: " + trek.toString());
|
||||||
|
|
||||||
// Double Brace Initialization
|
// Double Brace Initialization
|
||||||
// The Java Language has no syntax for how to create static Collections
|
// The Java Language has no syntax for how to create static Collections
|
||||||
// in an easy way. Usually you end up in the following way:
|
// in an easy way. Usually you end up in the following way:
|
||||||
|
|
||||||
private static final Set<String> COUNTRIES = new HashSet<String>();
|
private static final Set<String> COUNTRIES = new HashSet<String>();
|
||||||
static {
|
static {
|
||||||
validCodes.add("DENMARK");
|
validCodes.add("DENMARK");
|
||||||
validCodes.add("SWEDEN");
|
validCodes.add("SWEDEN");
|
||||||
validCodes.add("FINLAND");
|
validCodes.add("FINLAND");
|
||||||
}
|
}
|
||||||
|
|
||||||
// But there's a nifty way to achive the same thing in an
|
// But there's a nifty way to achive the same thing in an
|
||||||
// easier way, by using something that is called Double Brace
|
// easier way, by using something that is called Double Brace
|
||||||
// Initialization.
|
// Initialization.
|
||||||
|
|
||||||
private static final Set<String> COUNTRIES = HashSet<String>() {{
|
private static final Set<String> COUNTRIES = HashSet<String>() {{
|
||||||
add("DENMARK");
|
add("DENMARK");
|
||||||
add("SWEDEN");
|
add("SWEDEN");
|
||||||
add("FINLAND");
|
add("FINLAND");
|
||||||
}}
|
}}
|
||||||
|
|
||||||
// The first brace is creating an new AnonymousInnerClass and the
|
// The first brace is creating an new AnonymousInnerClass and the
|
||||||
// second one declares and instance initializer block. This block
|
// second one declares and instance initializer block. This block
|
||||||
// is called with the anonymous inner class is created.
|
// is called with the anonymous inner class is created.
|
||||||
// This does not only work for Collections, it works for all
|
// This does not only work for Collections, it works for all
|
||||||
@ -500,7 +500,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Abstract Classes
|
// Abstract Classes
|
||||||
// Abstract Class declaration syntax
|
// Abstract Class declaration syntax
|
||||||
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
||||||
// // Constants and variables
|
// // Constants and variables
|
||||||
@ -512,26 +512,26 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
|||||||
// Also abstract classes CAN have the "main" method.
|
// Also abstract classes CAN have the "main" method.
|
||||||
// Abstract classes solve these problems.
|
// Abstract classes solve these problems.
|
||||||
|
|
||||||
public abstract class Animal
|
public abstract class Animal
|
||||||
{
|
{
|
||||||
public abstract void makeSound();
|
public abstract void makeSound();
|
||||||
|
|
||||||
// Method can have a body
|
// Method can have a body
|
||||||
public void eat()
|
public void eat()
|
||||||
{
|
{
|
||||||
System.out.println("I am an animal and I am Eating.");
|
System.out.println("I am an animal and I am Eating.");
|
||||||
// Note: We can access private variable here.
|
// Note: We can access private variable here.
|
||||||
age = 30;
|
age = 30;
|
||||||
}
|
}
|
||||||
|
|
||||||
// No need to initialize, however in an interface
|
// No need to initialize, however in an interface
|
||||||
// a variable is implicitly final and hence has
|
// a variable is implicitly final and hence has
|
||||||
// to be initialized.
|
// to be initialized.
|
||||||
private int age;
|
private int age;
|
||||||
|
|
||||||
public void printAge()
|
public void printAge()
|
||||||
{
|
{
|
||||||
System.out.println(age);
|
System.out.println(age);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Abstract classes can have main function.
|
// Abstract classes can have main function.
|
||||||
@ -552,7 +552,7 @@ class Dog extends Animal
|
|||||||
// age = 30; ==> ERROR! age is private to Animal
|
// age = 30; ==> ERROR! age is private to Animal
|
||||||
}
|
}
|
||||||
|
|
||||||
// NOTE: You will get an error if you used the
|
// NOTE: You will get an error if you used the
|
||||||
// @Override annotation here, since java doesn't allow
|
// @Override annotation here, since java doesn't allow
|
||||||
// overriding of static methods.
|
// overriding of static methods.
|
||||||
// What is happening here is called METHOD HIDING.
|
// What is happening here is called METHOD HIDING.
|
||||||
|
@ -16,7 +16,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
|
|
||||||
"keys": "must always be enclosed in double quotes",
|
"keys": "must always be enclosed in double quotes",
|
||||||
"numbers": 0,
|
"numbers": 0,
|
||||||
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
|
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
|
||||||
@ -46,7 +46,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
|||||||
[0, 0, 0, 1]
|
[0, 0, 0, 1]
|
||||||
]
|
]
|
||||||
],
|
],
|
||||||
|
|
||||||
"alternative style": {
|
"alternative style": {
|
||||||
"comment": "check this out!"
|
"comment": "check this out!"
|
||||||
, "comma position": "doesn't matter - as long as it's before the value, then it's valid"
|
, "comma position": "doesn't matter - as long as it's before the value, then it's valid"
|
||||||
|
@ -14,7 +14,7 @@ This is based on Julia 0.3.
|
|||||||
|
|
||||||
# Single line comments start with a hash (pound) symbol.
|
# Single line comments start with a hash (pound) symbol.
|
||||||
#= Multiline comments can be written
|
#= Multiline comments can be written
|
||||||
by putting '#=' before the text and '=#'
|
by putting '#=' before the text and '=#'
|
||||||
after the text. They can also be nested.
|
after the text. They can also be nested.
|
||||||
=#
|
=#
|
||||||
|
|
||||||
@ -670,7 +670,7 @@ square_area(l) = l * l # square_area (generic function with 1 method)
|
|||||||
square_area(5) #25
|
square_area(5) #25
|
||||||
|
|
||||||
# What happens when we feed square_area an integer?
|
# What happens when we feed square_area an integer?
|
||||||
code_native(square_area, (Int32,))
|
code_native(square_area, (Int32,))
|
||||||
# .section __TEXT,__text,regular,pure_instructions
|
# .section __TEXT,__text,regular,pure_instructions
|
||||||
# Filename: none
|
# Filename: none
|
||||||
# Source line: 1 # Prologue
|
# Source line: 1 # Prologue
|
||||||
@ -703,10 +703,10 @@ code_native(square_area, (Float64,))
|
|||||||
# vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
|
# vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
# Note that julia will use floating point instructions if any of the
|
# Note that julia will use floating point instructions if any of the
|
||||||
# arguements are floats.
|
# arguements are floats.
|
||||||
# Let's calculate the area of a circle
|
# Let's calculate the area of a circle
|
||||||
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
|
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
|
||||||
circle_area(5) # 78.53981633974483
|
circle_area(5) # 78.53981633974483
|
||||||
|
|
||||||
@ -737,7 +737,7 @@ code_native(circle_area, (Float64,))
|
|||||||
# vmulsd XMM0, XMM1, XMM0
|
# vmulsd XMM0, XMM1, XMM0
|
||||||
# pop RBP
|
# pop RBP
|
||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
```
|
```
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
@ -166,7 +166,7 @@ not false # => true
|
|||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
## 3. Functions
|
## 3. Functions
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
# Since LiveScript is functional, you'd expect functions to get a nice
|
# Since LiveScript is functional, you'd expect functions to get a nice
|
||||||
# treatment. In LiveScript it's even more apparent that functions are
|
# treatment. In LiveScript it's even more apparent that functions are
|
||||||
@ -229,7 +229,7 @@ double-minus-one = (- 1) . (* 2)
|
|||||||
|
|
||||||
# Other than the usual `f . g` mathematical formulae, you get the `>>`
|
# Other than the usual `f . g` mathematical formulae, you get the `>>`
|
||||||
# and `<<` operators, that describe how the flow of values through the
|
# and `<<` operators, that describe how the flow of values through the
|
||||||
# functions.
|
# functions.
|
||||||
double-minus-one = (* 2) >> (- 1)
|
double-minus-one = (* 2) >> (- 1)
|
||||||
double-minus-one = (- 1) << (* 2)
|
double-minus-one = (- 1) << (* 2)
|
||||||
|
|
||||||
@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*"
|
|||||||
## Further reading
|
## Further reading
|
||||||
|
|
||||||
There's just so much more to LiveScript, but this should be enough to
|
There's just so much more to LiveScript, but this should be enough to
|
||||||
get you started writing little functional things in it. The
|
get you started writing little functional things in it. The
|
||||||
[official website](http://livescript.net/) has a lot of information on the
|
[official website](http://livescript.net/) has a lot of information on the
|
||||||
language, and a nice online compiler for you to try stuff out!
|
language, and a nice online compiler for you to try stuff out!
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ we are using GNU make which is the standard on Linux.
|
|||||||
file0.txt:
|
file0.txt:
|
||||||
echo "foo" > file0.txt
|
echo "foo" > file0.txt
|
||||||
# Even comments in these 'recipe' sections get passed to the shell.
|
# Even comments in these 'recipe' sections get passed to the shell.
|
||||||
# Try `make file0.txt` or simply `make` - first rule is the default.
|
# Try `make file0.txt` or simply `make` - first rule is the default.
|
||||||
|
|
||||||
|
|
||||||
# This rule will only run if file0.txt is newer than file1.txt.
|
# This rule will only run if file0.txt is newer than file1.txt.
|
||||||
@ -49,7 +49,7 @@ file2.txt file3.txt: file0.txt file1.txt
|
|||||||
touch file2.txt
|
touch file2.txt
|
||||||
touch file3.txt
|
touch file3.txt
|
||||||
|
|
||||||
# Make will complain about multiple recipes for the same rule. Empty
|
# Make will complain about multiple recipes for the same rule. Empty
|
||||||
# recipes don't count though and can be used to add new dependencies.
|
# recipes don't count though and can be used to add new dependencies.
|
||||||
|
|
||||||
#-----------------------------------------------------------------------
|
#-----------------------------------------------------------------------
|
||||||
@ -115,7 +115,7 @@ small/%.png: %.svg
|
|||||||
%.png: %.ps
|
%.png: %.ps
|
||||||
@echo this rule is not chosen if *.svg and *.ps are both present
|
@echo this rule is not chosen if *.svg and *.ps are both present
|
||||||
|
|
||||||
# make already has some pattern rules built-in. For instance, it knows
|
# make already has some pattern rules built-in. For instance, it knows
|
||||||
# how to turn *.c files into *.o files.
|
# how to turn *.c files into *.o files.
|
||||||
|
|
||||||
# Older makefiles might use suffix rules instead of pattern rules
|
# Older makefiles might use suffix rules instead of pattern rules
|
||||||
@ -185,7 +185,7 @@ var := hello
|
|||||||
var2 ::= $(var) hello
|
var2 ::= $(var) hello
|
||||||
#:= and ::= are equivalent.
|
#:= and ::= are equivalent.
|
||||||
|
|
||||||
# These variables are evaluated procedurely (in the order that they
|
# These variables are evaluated procedurely (in the order that they
|
||||||
# appear), thus breaking with the rest of the language !
|
# appear), thus breaking with the rest of the language !
|
||||||
|
|
||||||
# This doesn't work
|
# This doesn't work
|
||||||
|
@ -70,7 +70,7 @@ I'm in paragraph three!
|
|||||||
<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
|
<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
|
||||||
with two or more spaces and then begin a new paragraph. -->
|
with two or more spaces and then begin a new paragraph. -->
|
||||||
|
|
||||||
I end with two spaces (highlight me to see them).
|
I end with two spaces (highlight me to see them).
|
||||||
|
|
||||||
There's a <br /> above me!
|
There's a <br /> above me!
|
||||||
|
|
||||||
@ -97,7 +97,7 @@ or
|
|||||||
+ Item
|
+ Item
|
||||||
+ One more item
|
+ One more item
|
||||||
|
|
||||||
or
|
or
|
||||||
|
|
||||||
- Item
|
- Item
|
||||||
- Item
|
- Item
|
||||||
@ -129,7 +129,7 @@ render the numbers in order, but this may not be a good idea -->
|
|||||||
<!-- There are even task lists. This creates HTML checkboxes. -->
|
<!-- There are even task lists. This creates HTML checkboxes. -->
|
||||||
|
|
||||||
Boxes below without the 'x' are unchecked HTML checkboxes.
|
Boxes below without the 'x' are unchecked HTML checkboxes.
|
||||||
- [ ] First task to complete.
|
- [ ] First task to complete.
|
||||||
- [ ] Second task that needs done
|
- [ ] Second task that needs done
|
||||||
This checkbox below will be a checked HTML checkbox.
|
This checkbox below will be a checked HTML checkbox.
|
||||||
- [x] This task has been completed
|
- [x] This task has been completed
|
||||||
@ -169,7 +169,7 @@ with or without spaces. -->
|
|||||||
|
|
||||||
***
|
***
|
||||||
---
|
---
|
||||||
- - -
|
- - -
|
||||||
****************
|
****************
|
||||||
|
|
||||||
<!-- Links -->
|
<!-- Links -->
|
||||||
|
@ -6,7 +6,7 @@ contributors:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
|
MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
|
||||||
|
|
||||||
If you have any feedback please feel free to reach me at
|
If you have any feedback please feel free to reach me at
|
||||||
[@the_ozzinator](https://twitter.com/the_ozzinator), or
|
[@the_ozzinator](https://twitter.com/the_ozzinator), or
|
||||||
@ -16,7 +16,7 @@ If you have any feedback please feel free to reach me at
|
|||||||
% Comments start with a percent sign.
|
% Comments start with a percent sign.
|
||||||
|
|
||||||
%{
|
%{
|
||||||
Multi line comments look
|
Multi line comments look
|
||||||
something
|
something
|
||||||
like
|
like
|
||||||
this
|
this
|
||||||
@ -62,10 +62,10 @@ disp('text') % print "text" to the screen
|
|||||||
% Variables & Expressions
|
% Variables & Expressions
|
||||||
myVariable = 4 % Notice Workspace pane shows newly created variable
|
myVariable = 4 % Notice Workspace pane shows newly created variable
|
||||||
myVariable = 4; % Semi colon suppresses output to the Command Window
|
myVariable = 4; % Semi colon suppresses output to the Command Window
|
||||||
4 + 6 % ans = 10
|
4 + 6 % ans = 10
|
||||||
8 * myVariable % ans = 32
|
8 * myVariable % ans = 32
|
||||||
2 ^ 3 % ans = 8
|
2 ^ 3 % ans = 8
|
||||||
a = 2; b = 3;
|
a = 2; b = 3;
|
||||||
c = exp(a)*sin(pi/2) % c = 7.3891
|
c = exp(a)*sin(pi/2) % c = 7.3891
|
||||||
|
|
||||||
% Calling functions can be done in either of two ways:
|
% Calling functions can be done in either of two ways:
|
||||||
@ -73,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
|
|||||||
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
|
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
|
||||||
% Command syntax:
|
% Command syntax:
|
||||||
load myFile.mat y % no parentheses, and spaces instead of commas
|
load myFile.mat y % no parentheses, and spaces instead of commas
|
||||||
% Note the lack of quote marks in command form: inputs are always passed as
|
% Note the lack of quote marks in command form: inputs are always passed as
|
||||||
% literal text - cannot pass variable values. Also, can't receive output:
|
% literal text - cannot pass variable values. Also, can't receive output:
|
||||||
[V,D] = eig(A); % this has no equivalent in command form
|
[V,D] = eig(A); % this has no equivalent in command form
|
||||||
[~,D] = eig(A); % if you only want D and not V
|
[~,D] = eig(A); % if you only want D and not V
|
||||||
@ -103,7 +103,7 @@ a(2) % ans = y
|
|||||||
|
|
||||||
|
|
||||||
% Cells
|
% Cells
|
||||||
a = {'one', 'two', 'three'}
|
a = {'one', 'two', 'three'}
|
||||||
a(1) % ans = 'one' - returns a cell
|
a(1) % ans = 'one' - returns a cell
|
||||||
char(a(1)) % ans = one - returns a string
|
char(a(1)) % ans = one - returns a string
|
||||||
|
|
||||||
@ -113,7 +113,7 @@ A.c = [1 2];
|
|||||||
A.d.e = false;
|
A.d.e = false;
|
||||||
|
|
||||||
% Vectors
|
% Vectors
|
||||||
x = [4 32 53 7 1]
|
x = [4 32 53 7 1]
|
||||||
x(2) % ans = 32, indices in Matlab start 1, not 0
|
x(2) % ans = 32, indices in Matlab start 1, not 0
|
||||||
x(2:3) % ans = 32 53
|
x(2:3) % ans = 32 53
|
||||||
x(2:end) % ans = 32 53 7 1
|
x(2:end) % ans = 32 53 7 1
|
||||||
@ -123,7 +123,7 @@ x = [4; 32; 53; 7; 1] % Column vector
|
|||||||
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
|
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
|
||||||
|
|
||||||
% Matrices
|
% Matrices
|
||||||
A = [1 2 3; 4 5 6; 7 8 9]
|
A = [1 2 3; 4 5 6; 7 8 9]
|
||||||
% Rows are separated by a semicolon; elements are separated with space or comma
|
% Rows are separated by a semicolon; elements are separated with space or comma
|
||||||
% A =
|
% A =
|
||||||
|
|
||||||
@ -132,7 +132,7 @@ A = [1 2 3; 4 5 6; 7 8 9]
|
|||||||
% 7 8 9
|
% 7 8 9
|
||||||
|
|
||||||
A(2,3) % ans = 6, A(row, column)
|
A(2,3) % ans = 6, A(row, column)
|
||||||
A(6) % ans = 8
|
A(6) % ans = 8
|
||||||
% (implicitly concatenates columns into vector, then indexes into that)
|
% (implicitly concatenates columns into vector, then indexes into that)
|
||||||
|
|
||||||
|
|
||||||
@ -171,7 +171,7 @@ A(1,:) % All columns in row 1
|
|||||||
% 4 5 42
|
% 4 5 42
|
||||||
% 7 8 9
|
% 7 8 9
|
||||||
|
|
||||||
% this is the same as
|
% this is the same as
|
||||||
vertcat(A,A);
|
vertcat(A,A);
|
||||||
|
|
||||||
|
|
||||||
@ -183,7 +183,7 @@ vertcat(A,A);
|
|||||||
% 4 5 42 4 5 42
|
% 4 5 42 4 5 42
|
||||||
% 7 8 9 7 8 9
|
% 7 8 9 7 8 9
|
||||||
|
|
||||||
% this is the same as
|
% this is the same as
|
||||||
horzcat(A,A);
|
horzcat(A,A);
|
||||||
|
|
||||||
|
|
||||||
@ -201,21 +201,21 @@ A(:, 1) =[] % Delete the first column of the matrix
|
|||||||
|
|
||||||
transpose(A) % Transpose the matrix, which is the same as:
|
transpose(A) % Transpose the matrix, which is the same as:
|
||||||
A one
|
A one
|
||||||
ctranspose(A) % Hermitian transpose the matrix
|
ctranspose(A) % Hermitian transpose the matrix
|
||||||
% (the transpose, followed by taking complex conjugate of each element)
|
% (the transpose, followed by taking complex conjugate of each element)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
% Element by Element Arithmetic vs. Matrix Arithmetic
|
% Element by Element Arithmetic vs. Matrix Arithmetic
|
||||||
% On their own, the arithmetic operators act on whole matrices. When preceded
|
% On their own, the arithmetic operators act on whole matrices. When preceded
|
||||||
% by a period, they act on each element instead. For example:
|
% by a period, they act on each element instead. For example:
|
||||||
A * B % Matrix multiplication
|
A * B % Matrix multiplication
|
||||||
A .* B % Multiple each element in A by its corresponding element in B
|
A .* B % Multiple each element in A by its corresponding element in B
|
||||||
|
|
||||||
% There are several pairs of functions, where one acts on each element, and
|
% There are several pairs of functions, where one acts on each element, and
|
||||||
% the other (whose name ends in m) acts on the whole matrix.
|
% the other (whose name ends in m) acts on the whole matrix.
|
||||||
exp(A) % exponentiate each element
|
exp(A) % exponentiate each element
|
||||||
expm(A) % calculate the matrix exponential
|
expm(A) % calculate the matrix exponential
|
||||||
sqrt(A) % take the square root of each element
|
sqrt(A) % take the square root of each element
|
||||||
sqrtm(A) % find the matrix whose square is A
|
sqrtm(A) % find the matrix whose square is A
|
||||||
@ -233,7 +233,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1
|
|||||||
plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot
|
plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot
|
||||||
legend('Line 1 label', 'Line 2 label') % Label curves with a legend
|
legend('Line 1 label', 'Line 2 label') % Label curves with a legend
|
||||||
|
|
||||||
% Alternative method to plot multiple functions in one plot.
|
% Alternative method to plot multiple functions in one plot.
|
||||||
% while 'hold' is on, commands add to existing graph rather than replacing it
|
% while 'hold' is on, commands add to existing graph rather than replacing it
|
||||||
plot(x, y)
|
plot(x, y)
|
||||||
hold on
|
hold on
|
||||||
@ -271,9 +271,9 @@ clf clear % clear current figure window, and reset most figure properties
|
|||||||
|
|
||||||
% Properties can be set and changed through a figure handle.
|
% Properties can be set and changed through a figure handle.
|
||||||
% You can save a handle to a figure when you create it.
|
% You can save a handle to a figure when you create it.
|
||||||
% The function gcf returns a handle to the current figure
|
% The function gcf returns a handle to the current figure
|
||||||
h = plot(x, y); % you can save a handle to a figure when you create it
|
h = plot(x, y); % you can save a handle to a figure when you create it
|
||||||
set(h, 'Color', 'r')
|
set(h, 'Color', 'r')
|
||||||
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
||||||
set(h, 'LineStyle', '--')
|
set(h, 'LineStyle', '--')
|
||||||
% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line
|
% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line
|
||||||
@ -298,8 +298,8 @@ cd /path/to/move/into % change directory
|
|||||||
|
|
||||||
|
|
||||||
% Variables can be saved to .mat files
|
% Variables can be saved to .mat files
|
||||||
save('myFileName.mat') % Save the variables in your Workspace
|
save('myFileName.mat') % Save the variables in your Workspace
|
||||||
load('myFileName.mat') % Load saved variables into Workspace
|
load('myFileName.mat') % Load saved variables into Workspace
|
||||||
|
|
||||||
% M-file Scripts
|
% M-file Scripts
|
||||||
% A script file is an external file that contains a sequence of statements.
|
% A script file is an external file that contains a sequence of statements.
|
||||||
@ -312,11 +312,11 @@ load('myFileName.mat') % Load saved variables into Workspace
|
|||||||
% Also, they have their own workspace (ie. different variable scope).
|
% Also, they have their own workspace (ie. different variable scope).
|
||||||
% Function name should match file name (so save this example as double_input.m).
|
% Function name should match file name (so save this example as double_input.m).
|
||||||
% 'help double_input.m' returns the comments under line beginning function
|
% 'help double_input.m' returns the comments under line beginning function
|
||||||
function output = double_input(x)
|
function output = double_input(x)
|
||||||
%double_input(x) returns twice the value of x
|
%double_input(x) returns twice the value of x
|
||||||
output = 2*x;
|
output = 2*x;
|
||||||
end
|
end
|
||||||
double_input(6) % ans = 12
|
double_input(6) % ans = 12
|
||||||
|
|
||||||
|
|
||||||
% You can also have subfunctions and nested functions.
|
% You can also have subfunctions and nested functions.
|
||||||
@ -325,8 +325,8 @@ double_input(6) % ans = 12
|
|||||||
% functions, and have access to both its workspace and their own workspace.
|
% functions, and have access to both its workspace and their own workspace.
|
||||||
|
|
||||||
% If you want to create a function without creating a new file you can use an
|
% If you want to create a function without creating a new file you can use an
|
||||||
% anonymous function. Useful when quickly defining a function to pass to
|
% anonymous function. Useful when quickly defining a function to pass to
|
||||||
% another function (eg. plot with fplot, evaluate an indefinite integral
|
% another function (eg. plot with fplot, evaluate an indefinite integral
|
||||||
% with quad, find roots with fzero, or find minimum with fminsearch).
|
% with quad, find roots with fzero, or find minimum with fminsearch).
|
||||||
% Example that returns the square of it's input, assigned to to the handle sqr:
|
% Example that returns the square of it's input, assigned to to the handle sqr:
|
||||||
sqr = @(x) x.^2;
|
sqr = @(x) x.^2;
|
||||||
@ -336,12 +336,12 @@ doc function_handle % find out more
|
|||||||
% User input
|
% User input
|
||||||
a = input('Enter the value: ')
|
a = input('Enter the value: ')
|
||||||
|
|
||||||
% Stops execution of file and gives control to the keyboard: user can examine
|
% Stops execution of file and gives control to the keyboard: user can examine
|
||||||
% or change variables. Type 'return' to continue execution, or 'dbquit' to exit
|
% or change variables. Type 'return' to continue execution, or 'dbquit' to exit
|
||||||
keyboard
|
keyboard
|
||||||
|
|
||||||
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
|
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
|
||||||
fopen(filename)
|
fopen(filename)
|
||||||
|
|
||||||
% Output
|
% Output
|
||||||
disp(a) % Print out the value of variable a
|
disp(a) % Print out the value of variable a
|
||||||
@ -363,8 +363,8 @@ end
|
|||||||
for k = 1:5
|
for k = 1:5
|
||||||
disp(k)
|
disp(k)
|
||||||
end
|
end
|
||||||
|
|
||||||
k = 0;
|
k = 0;
|
||||||
while (k < 5)
|
while (k < 5)
|
||||||
k = k + 1;
|
k = k + 1;
|
||||||
end
|
end
|
||||||
@ -382,7 +382,7 @@ password = 'root';
|
|||||||
driver = 'com.mysql.jdbc.Driver';
|
driver = 'com.mysql.jdbc.Driver';
|
||||||
dburl = ['jdbc:mysql://localhost:8889/' dbname];
|
dburl = ['jdbc:mysql://localhost:8889/' dbname];
|
||||||
javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
|
javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
|
||||||
conn = database(dbname, username, password, driver, dburl);
|
conn = database(dbname, username, password, driver, dburl);
|
||||||
sql = ['SELECT * from table_name where id = 22'] % Example sql statement
|
sql = ['SELECT * from table_name where id = 22'] % Example sql statement
|
||||||
a = fetch(conn, sql) %a will contain your data
|
a = fetch(conn, sql) %a will contain your data
|
||||||
|
|
||||||
@ -394,7 +394,7 @@ tan(x)
|
|||||||
asin(x)
|
asin(x)
|
||||||
acos(x)
|
acos(x)
|
||||||
atan(x)
|
atan(x)
|
||||||
exp(x)
|
exp(x)
|
||||||
sqrt(x)
|
sqrt(x)
|
||||||
log(x)
|
log(x)
|
||||||
log10(x)
|
log10(x)
|
||||||
@ -426,7 +426,7 @@ pinv(A) % calculate the pseudo-inverse
|
|||||||
zeros(m,n) % m x n matrix of 0's
|
zeros(m,n) % m x n matrix of 0's
|
||||||
ones(m,n) % m x n matrix of 1's
|
ones(m,n) % m x n matrix of 1's
|
||||||
diag(A) % Extracts the diagonal elements of a matrix A
|
diag(A) % Extracts the diagonal elements of a matrix A
|
||||||
diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
|
diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
|
||||||
eye(m,n) % Identity matrix
|
eye(m,n) % Identity matrix
|
||||||
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
|
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
|
||||||
inv(A) % Inverse of matrix A
|
inv(A) % Inverse of matrix A
|
||||||
@ -452,15 +452,15 @@ flipud(A) % Flip matrix up to down
|
|||||||
[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order
|
[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order
|
||||||
|
|
||||||
% Common vector functions
|
% Common vector functions
|
||||||
max % largest component
|
max % largest component
|
||||||
min % smallest component
|
min % smallest component
|
||||||
length % length of a vector
|
length % length of a vector
|
||||||
sort % sort in ascending order
|
sort % sort in ascending order
|
||||||
sum % sum of elements
|
sum % sum of elements
|
||||||
prod % product of elements
|
prod % product of elements
|
||||||
mode % modal value
|
mode % modal value
|
||||||
median % median value
|
median % median value
|
||||||
mean % mean value
|
mean % mean value
|
||||||
std % standard deviation
|
std % standard deviation
|
||||||
perms(x) % list all permutations of elements of x
|
perms(x) % list all permutations of elements of x
|
||||||
|
|
||||||
|
@ -47,18 +47,18 @@ void main(string[] args) {
|
|||||||
// There are no one-value tuples though.
|
// There are no one-value tuples though.
|
||||||
// So you can always use () in the mathematical sense.
|
// So you can always use () in the mathematical sense.
|
||||||
// (string) arg; <- is an error
|
// (string) arg; <- is an error
|
||||||
|
|
||||||
/*
|
/*
|
||||||
byte: 8 bit signed integer
|
byte: 8 bit signed integer
|
||||||
char: 8 bit UTF-8 byte component.
|
char: 8 bit UTF-8 byte component.
|
||||||
short: 16 bit signed integer
|
short: 16 bit signed integer
|
||||||
int: 32 bit signed integer
|
int: 32 bit signed integer
|
||||||
long: 64 bit signed integer
|
long: 64 bit signed integer
|
||||||
|
|
||||||
float: 32 bit floating point
|
float: 32 bit floating point
|
||||||
double: 64 bit floating point
|
double: 64 bit floating point
|
||||||
real: biggest native size floating point (80 bit on x86).
|
real: biggest native size floating point (80 bit on x86).
|
||||||
|
|
||||||
bool: true or false
|
bool: true or false
|
||||||
*/
|
*/
|
||||||
int a = 5;
|
int a = 5;
|
||||||
@ -139,14 +139,14 @@ void main(string[] args) {
|
|||||||
assert !(hewo is s);
|
assert !(hewo is s);
|
||||||
// same as
|
// same as
|
||||||
assert (hewo !is s);
|
assert (hewo !is s);
|
||||||
|
|
||||||
// Allocate arrays using "new array length"
|
// Allocate arrays using "new array length"
|
||||||
int[] integers = new int[] 10;
|
int[] integers = new int[] 10;
|
||||||
assert(integers.length == 10);
|
assert(integers.length == 10);
|
||||||
assert(integers[0] == 0); // zero is default initializer
|
assert(integers[0] == 0); // zero is default initializer
|
||||||
integers = integers ~ 5; // This allocates a new array!
|
integers = integers ~ 5; // This allocates a new array!
|
||||||
assert(integers.length == 11);
|
assert(integers.length == 11);
|
||||||
|
|
||||||
// This is an appender array.
|
// This is an appender array.
|
||||||
// Instead of (length, pointer), it tracks (capacity, length, pointer).
|
// Instead of (length, pointer), it tracks (capacity, length, pointer).
|
||||||
// When you append to it, it will use the free capacity if it can.
|
// When you append to it, it will use the free capacity if it can.
|
||||||
@ -156,13 +156,13 @@ void main(string[] args) {
|
|||||||
appender ~= 2;
|
appender ~= 2;
|
||||||
appender ~= 3;
|
appender ~= 3;
|
||||||
appender.free(); // same as {mem.free(appender.ptr); appender = null;}
|
appender.free(); // same as {mem.free(appender.ptr); appender = null;}
|
||||||
|
|
||||||
// Scope variables are automatically freed at the end of the current scope.
|
// Scope variables are automatically freed at the end of the current scope.
|
||||||
scope int[auto~] someOtherAppender;
|
scope int[auto~] someOtherAppender;
|
||||||
// This is the same as:
|
// This is the same as:
|
||||||
int[auto~] someOtherAppender2;
|
int[auto~] someOtherAppender2;
|
||||||
onExit { someOtherAppender2.free; }
|
onExit { someOtherAppender2.free; }
|
||||||
|
|
||||||
// You can do a C for loop too
|
// You can do a C for loop too
|
||||||
// - but why would you want to?
|
// - but why would you want to?
|
||||||
for (int i = 0; i < 5; ++i) { }
|
for (int i = 0; i < 5; ++i) { }
|
||||||
@ -178,23 +178,23 @@ void main(string[] args) {
|
|||||||
assert(i == 5);
|
assert(i == 5);
|
||||||
break; // otherwise we'd go back up to do {
|
break; // otherwise we'd go back up to do {
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is a nested function.
|
// This is a nested function.
|
||||||
// Nested functions can access the surrounding function.
|
// Nested functions can access the surrounding function.
|
||||||
string returnS() { return s; }
|
string returnS() { return s; }
|
||||||
writeln returnS();
|
writeln returnS();
|
||||||
|
|
||||||
// Take the address of a function using &
|
// Take the address of a function using &
|
||||||
// The type of a global function is ReturnType function(ParameterTypeTuple).
|
// The type of a global function is ReturnType function(ParameterTypeTuple).
|
||||||
void function() foop = &foo;
|
void function() foop = &foo;
|
||||||
|
|
||||||
// Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
|
// Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
|
||||||
string delegate() returnSp = &returnS;
|
string delegate() returnSp = &returnS;
|
||||||
writeln returnSp();
|
writeln returnSp();
|
||||||
// Class member functions and struct member functions also fit into delegate variables.
|
// Class member functions and struct member functions also fit into delegate variables.
|
||||||
// In general, delegates are functions that carry an additional context pointer.
|
// In general, delegates are functions that carry an additional context pointer.
|
||||||
// ("fat pointers" in C)
|
// ("fat pointers" in C)
|
||||||
|
|
||||||
// Allocate a "snapshot" with "new delegate".
|
// Allocate a "snapshot" with "new delegate".
|
||||||
// Snapshots are not closures! I used to call them closures too,
|
// Snapshots are not closures! I used to call them closures too,
|
||||||
// but then my Haskell-using friends yelled at me so I had to stop.
|
// but then my Haskell-using friends yelled at me so I had to stop.
|
||||||
@ -232,8 +232,8 @@ void main(string[] args) {
|
|||||||
auto nestfun = λ() { } // There is NO semicolon needed here!
|
auto nestfun = λ() { } // There is NO semicolon needed here!
|
||||||
// "}" can always substitute for "};".
|
// "}" can always substitute for "};".
|
||||||
// This provides syntactic consistency with built-in statements.
|
// This provides syntactic consistency with built-in statements.
|
||||||
|
|
||||||
|
|
||||||
// This is a class.
|
// This is a class.
|
||||||
// Note: almost all elements of Neat can be used on the module level
|
// Note: almost all elements of Neat can be used on the module level
|
||||||
// or just as well inside a function.
|
// or just as well inside a function.
|
||||||
@ -268,7 +268,7 @@ void main(string[] args) {
|
|||||||
E e = E:cd; // dynamic class cast!
|
E e = E:cd; // dynamic class cast!
|
||||||
e.doE();
|
e.doE();
|
||||||
writeln "$e"; // all interfaces convert to Object implicitly.
|
writeln "$e"; // all interfaces convert to Object implicitly.
|
||||||
|
|
||||||
// Templates!
|
// Templates!
|
||||||
// Templates are parameterized namespaces, taking a type as a parameter.
|
// Templates are parameterized namespaces, taking a type as a parameter.
|
||||||
template Templ(T) {
|
template Templ(T) {
|
||||||
|
@ -11,7 +11,7 @@ filename: LearnObjectiveC.m
|
|||||||
---
|
---
|
||||||
|
|
||||||
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
||||||
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
|
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
|
||||||
|
|
||||||
```objective_c
|
```objective_c
|
||||||
// Single-line comments start with //
|
// Single-line comments start with //
|
||||||
@ -41,15 +41,15 @@ int main (int argc, const char * argv[])
|
|||||||
|
|
||||||
// Use NSLog to print lines to the console
|
// Use NSLog to print lines to the console
|
||||||
NSLog(@"Hello World!"); // Print the string "Hello World!"
|
NSLog(@"Hello World!"); // Print the string "Hello World!"
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Types & Variables
|
// Types & Variables
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
// Primitive declarations
|
// Primitive declarations
|
||||||
int myPrimitive1 = 1;
|
int myPrimitive1 = 1;
|
||||||
long myPrimitive2 = 234554664565;
|
long myPrimitive2 = 234554664565;
|
||||||
|
|
||||||
// Object declarations
|
// Object declarations
|
||||||
// Put the * in front of the variable names for strongly-typed object declarations
|
// Put the * in front of the variable names for strongly-typed object declarations
|
||||||
MyClass *myObject1 = nil; // Strong typing
|
MyClass *myObject1 = nil; // Strong typing
|
||||||
@ -57,15 +57,15 @@ int main (int argc, const char * argv[])
|
|||||||
// %@ is an object
|
// %@ is an object
|
||||||
// 'description' is a convention to display the value of the Objects
|
// 'description' is a convention to display the value of the Objects
|
||||||
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)"
|
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)"
|
||||||
|
|
||||||
// String
|
// String
|
||||||
NSString *worldString = @"World";
|
NSString *worldString = @"World";
|
||||||
NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
|
NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
|
||||||
// NSMutableString is a mutable version of the NSString object
|
// NSMutableString is a mutable version of the NSString object
|
||||||
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
|
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
|
||||||
[mutableString appendString:@" World!"];
|
[mutableString appendString:@" World!"];
|
||||||
NSLog(@"%@", mutableString); // prints => "Hello World!"
|
NSLog(@"%@", mutableString); // prints => "Hello World!"
|
||||||
|
|
||||||
// Character literals
|
// Character literals
|
||||||
NSNumber *theLetterZNumber = @'Z';
|
NSNumber *theLetterZNumber = @'Z';
|
||||||
char theLetterZ = [theLetterZNumber charValue]; // or 'Z'
|
char theLetterZ = [theLetterZNumber charValue]; // or 'Z'
|
||||||
@ -75,11 +75,11 @@ int main (int argc, const char * argv[])
|
|||||||
NSNumber *fortyTwoNumber = @42;
|
NSNumber *fortyTwoNumber = @42;
|
||||||
int fortyTwo = [fortyTwoNumber intValue]; // or 42
|
int fortyTwo = [fortyTwoNumber intValue]; // or 42
|
||||||
NSLog(@"%i", fortyTwo);
|
NSLog(@"%i", fortyTwo);
|
||||||
|
|
||||||
NSNumber *fortyTwoUnsignedNumber = @42U;
|
NSNumber *fortyTwoUnsignedNumber = @42U;
|
||||||
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
|
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
|
||||||
NSLog(@"%u", fortyTwoUnsigned);
|
NSLog(@"%u", fortyTwoUnsigned);
|
||||||
|
|
||||||
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
|
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
|
||||||
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42
|
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42
|
||||||
NSLog(@"%hi", fortyTwoShort);
|
NSLog(@"%hi", fortyTwoShort);
|
||||||
@ -87,7 +87,7 @@ int main (int argc, const char * argv[])
|
|||||||
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
|
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
|
||||||
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
|
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
|
||||||
NSLog(@"%u", fortyOneUnsigned);
|
NSLog(@"%u", fortyOneUnsigned);
|
||||||
|
|
||||||
NSNumber *fortyTwoLongNumber = @42L;
|
NSNumber *fortyTwoLongNumber = @42L;
|
||||||
long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42
|
long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42
|
||||||
NSLog(@"%li", fortyTwoLong);
|
NSLog(@"%li", fortyTwoLong);
|
||||||
@ -101,7 +101,7 @@ int main (int argc, const char * argv[])
|
|||||||
float piFloat = [piFloatNumber floatValue]; // or 3.141592654f
|
float piFloat = [piFloatNumber floatValue]; // or 3.141592654f
|
||||||
NSLog(@"%f", piFloat); // prints => 3.141592654
|
NSLog(@"%f", piFloat); // prints => 3.141592654
|
||||||
NSLog(@"%5.2f", piFloat); // prints => " 3.14"
|
NSLog(@"%5.2f", piFloat); // prints => " 3.14"
|
||||||
|
|
||||||
NSNumber *piDoubleNumber = @3.1415926535;
|
NSNumber *piDoubleNumber = @3.1415926535;
|
||||||
double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535
|
double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535
|
||||||
NSLog(@"%f", piDouble);
|
NSLog(@"%f", piDouble);
|
||||||
@ -111,7 +111,7 @@ int main (int argc, const char * argv[])
|
|||||||
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
|
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
|
||||||
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
|
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
|
||||||
// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
|
// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
|
||||||
[oneDecNum decimalNumberByAdding:twoDecNum];
|
[oneDecNum decimalNumberByAdding:twoDecNum];
|
||||||
[oneDecNum decimalNumberBySubtracting:twoDecNum];
|
[oneDecNum decimalNumberBySubtracting:twoDecNum];
|
||||||
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
|
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
|
||||||
[oneDecNum decimalNumberByDividingBy:twoDecNum];
|
[oneDecNum decimalNumberByDividingBy:twoDecNum];
|
||||||
@ -130,8 +130,8 @@ int main (int argc, const char * argv[])
|
|||||||
NSArray *anArray = @[@1, @2, @3, @4];
|
NSArray *anArray = @[@1, @2, @3, @4];
|
||||||
NSNumber *thirdNumber = anArray[2];
|
NSNumber *thirdNumber = anArray[2];
|
||||||
NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3"
|
NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3"
|
||||||
// NSMutableArray is a mutable version of NSArray, allowing you to change
|
// NSMutableArray is a mutable version of NSArray, allowing you to change
|
||||||
// the items in the array and to extend or shrink the array object.
|
// the items in the array and to extend or shrink the array object.
|
||||||
// Convenient, but not as efficient as NSArray.
|
// Convenient, but not as efficient as NSArray.
|
||||||
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
|
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
|
||||||
[mutableArray addObject:@"Hello"];
|
[mutableArray addObject:@"Hello"];
|
||||||
@ -161,7 +161,7 @@ int main (int argc, const char * argv[])
|
|||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Operators
|
// Operators
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
// The operators works like in the C language
|
// The operators works like in the C language
|
||||||
// For example:
|
// For example:
|
||||||
2 + 5; // => 7
|
2 + 5; // => 7
|
||||||
@ -206,13 +206,13 @@ int main (int argc, const char * argv[])
|
|||||||
NSLog(@"I print");
|
NSLog(@"I print");
|
||||||
} break;
|
} break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// While loops statements
|
// While loops statements
|
||||||
int ii = 0;
|
int ii = 0;
|
||||||
while (ii < 4)
|
while (ii < 4)
|
||||||
{
|
{
|
||||||
NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
|
NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
|
||||||
} // prints => "0,"
|
} // prints => "0,"
|
||||||
// "1,"
|
// "1,"
|
||||||
// "2,"
|
// "2,"
|
||||||
// "3,"
|
// "3,"
|
||||||
@ -222,25 +222,25 @@ int main (int argc, const char * argv[])
|
|||||||
for (jj=0; jj < 4; jj++)
|
for (jj=0; jj < 4; jj++)
|
||||||
{
|
{
|
||||||
NSLog(@"%d,", jj);
|
NSLog(@"%d,", jj);
|
||||||
} // prints => "0,"
|
} // prints => "0,"
|
||||||
// "1,"
|
// "1,"
|
||||||
// "2,"
|
// "2,"
|
||||||
// "3,"
|
// "3,"
|
||||||
|
|
||||||
// Foreach statements
|
// Foreach statements
|
||||||
NSArray *values = @[@0, @1, @2, @3];
|
NSArray *values = @[@0, @1, @2, @3];
|
||||||
for (NSNumber *value in values)
|
for (NSNumber *value in values)
|
||||||
{
|
{
|
||||||
NSLog(@"%@,", value);
|
NSLog(@"%@,", value);
|
||||||
} // prints => "0,"
|
} // prints => "0,"
|
||||||
// "1,"
|
// "1,"
|
||||||
// "2,"
|
// "2,"
|
||||||
// "3,"
|
// "3,"
|
||||||
|
|
||||||
// Object for loop statement. Can be used with any Objective-C object type
|
// Object for loop statement. Can be used with any Objective-C object type
|
||||||
for (id item in values) {
|
for (id item in values) {
|
||||||
NSLog(@"%@,", item);
|
NSLog(@"%@,", item);
|
||||||
} // prints => "0,"
|
} // prints => "0,"
|
||||||
// "1,"
|
// "1,"
|
||||||
// "2,"
|
// "2,"
|
||||||
// "3,"
|
// "3,"
|
||||||
@ -251,7 +251,7 @@ int main (int argc, const char * argv[])
|
|||||||
// Your statements here
|
// Your statements here
|
||||||
@throw [NSException exceptionWithName:@"FileNotFoundException"
|
@throw [NSException exceptionWithName:@"FileNotFoundException"
|
||||||
reason:@"File Not Found on System" userInfo:nil];
|
reason:@"File Not Found on System" userInfo:nil];
|
||||||
} @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
|
} @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
|
||||||
{
|
{
|
||||||
NSLog(@"Exception: %@", e);
|
NSLog(@"Exception: %@", e);
|
||||||
} @finally
|
} @finally
|
||||||
@ -260,17 +260,17 @@ int main (int argc, const char * argv[])
|
|||||||
} // prints => "Exception: File Not Found on System"
|
} // prints => "Exception: File Not Found on System"
|
||||||
// "Finally. Time to clean up."
|
// "Finally. Time to clean up."
|
||||||
|
|
||||||
// NSError objects are useful for function arguments to populate on user mistakes.
|
// NSError objects are useful for function arguments to populate on user mistakes.
|
||||||
NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
|
NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Objects
|
// Objects
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
// Create an object instance by allocating memory and initializing it
|
// Create an object instance by allocating memory and initializing it
|
||||||
// An object is not fully functional until both steps have been completed
|
// An object is not fully functional until both steps have been completed
|
||||||
MyClass *myObject = [[MyClass alloc] init];
|
MyClass *myObject = [[MyClass alloc] init];
|
||||||
|
|
||||||
// The Objective-C model of object-oriented programming is based on message
|
// The Objective-C model of object-oriented programming is based on message
|
||||||
// passing to object instances
|
// passing to object instances
|
||||||
// In Objective-C one does not simply call a method; one sends a message
|
// In Objective-C one does not simply call a method; one sends a message
|
||||||
@ -281,7 +281,7 @@ int main (int argc, const char * argv[])
|
|||||||
|
|
||||||
// End of @autoreleasepool
|
// End of @autoreleasepool
|
||||||
}
|
}
|
||||||
|
|
||||||
// End the program
|
// End the program
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@ -302,9 +302,9 @@ int main (int argc, const char * argv[])
|
|||||||
@interface MyClass : NSObject <MyProtocol> // NSObject is Objective-C's base object class.
|
@interface MyClass : NSObject <MyProtocol> // NSObject is Objective-C's base object class.
|
||||||
{
|
{
|
||||||
// Instance variable declarations (can exist in either interface or implementation file)
|
// Instance variable declarations (can exist in either interface or implementation file)
|
||||||
int count; // Protected access by default.
|
int count; // Protected access by default.
|
||||||
@private id data; // Private access (More convenient to declare in implementation file)
|
@private id data; // Private access (More convenient to declare in implementation file)
|
||||||
NSString *name;
|
NSString *name;
|
||||||
}
|
}
|
||||||
// Convenient notation for public access variables to auto generate a setter method
|
// Convenient notation for public access variables to auto generate a setter method
|
||||||
// By default, setter method name is 'set' followed by @property variable name
|
// By default, setter method name is 'set' followed by @property variable name
|
||||||
@ -314,7 +314,7 @@ int main (int argc, const char * argv[])
|
|||||||
@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor
|
@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:
|
// You can customize the getter and setter names instead of using default 'set' name:
|
||||||
@property (getter=lengthGet, setter=lengthSet:) int length;
|
@property (getter=lengthGet, setter=lengthSet:) int length;
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
+/- (return type)methodSignature:(Parameter Type *)parameterName;
|
+/- (return type)methodSignature:(Parameter Type *)parameterName;
|
||||||
|
|
||||||
@ -336,7 +336,7 @@ int main (int argc, const char * argv[])
|
|||||||
// To access public variables from the implementation file, @property generates a setter method
|
// To access public variables from the implementation file, @property generates a setter method
|
||||||
// automatically. Method name is 'set' followed by @property variable name:
|
// automatically. Method name is 'set' followed by @property variable name:
|
||||||
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
|
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
|
||||||
[myClass setCount:10];
|
[myClass setCount:10];
|
||||||
NSLog(@"%d", [myClass count]); // prints => 10
|
NSLog(@"%d", [myClass count]); // prints => 10
|
||||||
// Or using the custom getter and setter method defined in @interface:
|
// Or using the custom getter and setter method defined in @interface:
|
||||||
[myClass lengthSet:32];
|
[myClass lengthSet:32];
|
||||||
@ -359,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell
|
|||||||
// as a variable
|
// as a variable
|
||||||
// SEL is the data type. @selector() returns a selector from method name provided
|
// SEL is the data type. @selector() returns a selector from method name provided
|
||||||
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
|
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
|
||||||
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
|
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
|
||||||
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
|
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
|
||||||
// Must put all method arguments into one object to send to performSelector function
|
// Must put all method arguments into one object to send to performSelector function
|
||||||
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
|
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
|
||||||
@ -383,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
@synthesize roString = _roString; // _roString available now in @implementation
|
@synthesize roString = _roString; // _roString available now in @implementation
|
||||||
|
|
||||||
// Called before calling any class methods or instantiating any objects
|
// Called before calling any class methods or instantiating any objects
|
||||||
+ (void)initialize
|
+ (void)initialize
|
||||||
{
|
{
|
||||||
if (self == [MyClass class]) {
|
if (self == [MyClass class]) {
|
||||||
distance = 0;
|
distance = 0;
|
||||||
@ -393,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
// Counterpart to initialize method. Called when an object's reference count is zero
|
// Counterpart to initialize method. Called when an object's reference count is zero
|
||||||
- (void)dealloc
|
- (void)dealloc
|
||||||
{
|
{
|
||||||
[height release]; // If not using ARC, make sure to release class variable objects
|
[height release]; // If not using ARC, make sure to release class variable objects
|
||||||
[super dealloc]; // and call parent class dealloc
|
[super dealloc]; // and call parent class dealloc
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -408,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
// Can create constructors that contain arguments:
|
// Can create constructors that contain arguments:
|
||||||
- (id)initWithDistance:(int)defaultDistance
|
- (id)initWithDistance:(int)defaultDistance
|
||||||
{
|
{
|
||||||
distance = defaultDistance;
|
distance = defaultDistance;
|
||||||
return self;
|
return self;
|
||||||
@ -419,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
return @"Some string";
|
return @"Some string";
|
||||||
}
|
}
|
||||||
|
|
||||||
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
|
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
|
||||||
{
|
{
|
||||||
height = defaultHeight;
|
height = defaultHeight;
|
||||||
return [[self alloc] init];
|
return [[self alloc] init];
|
||||||
@ -435,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
return @42;
|
return @42;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Objective-C does not have private method declarations, but you can simulate them.
|
// Objective-C does not have private method declarations, but you can simulate them.
|
||||||
// To simulate a private method, create the method in the @implementation but not in the @interface.
|
// To simulate a private method, create the method in the @implementation but not in the @interface.
|
||||||
- (NSNumber *)secretPrivateMethod {
|
- (NSNumber *)secretPrivateMethod {
|
||||||
return @72;
|
return @72;
|
||||||
@ -454,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
// Categories
|
// Categories
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// A category is a group of methods designed to extend a class. They allow you to add new methods
|
// A category is a group of methods designed to extend a class. They allow you to add new methods
|
||||||
// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
|
// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
|
||||||
// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
|
// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
|
||||||
// functionality to an object.
|
// functionality to an object.
|
||||||
// Categories allow you to:
|
// Categories allow you to:
|
||||||
// -- Add methods to an existing class for organizational purposes.
|
// -- Add methods to an existing class for organizational purposes.
|
||||||
// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
|
// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
|
||||||
// -- Add ability to create protected and private methods to classes.
|
// -- Add ability to create protected and private methods to classes.
|
||||||
// NOTE: Do not override methods of the base class in a category even though you have the ability
|
// NOTE: Do not override methods of the base class in a category even though you have the ability
|
||||||
// to. Overriding methods may cause compiler errors later between different categories and it
|
// to. Overriding methods may cause compiler errors later between different categories and it
|
||||||
// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.
|
// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.
|
||||||
|
|
||||||
// Here is a simple Car base class.
|
// Here is a simple Car base class.
|
||||||
@ -494,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
@end
|
@end
|
||||||
|
|
||||||
// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
|
// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
|
||||||
// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
|
// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
|
||||||
// functionality to this existing Car. A good example would be to clean the car. So we would create
|
// functionality to this existing Car. A good example would be to clean the car. So we would create
|
||||||
// a category to add these cleaning methods:
|
// a category to add these cleaning methods:
|
||||||
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
|
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
|
||||||
#import "Car.h" // Make sure to import base class to extend.
|
#import "Car.h" // Make sure to import base class to extend.
|
||||||
@ -519,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
|||||||
NSLog(@"Waxed.");
|
NSLog(@"Waxed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
// Any Car object instance has the ability to use a category. All they need to do is import it:
|
// Any Car object instance has the ability to use a category. All they need to do is import it:
|
||||||
#import "Car+Clean.h" // Import as many different categories as you want to use.
|
#import "Car+Clean.h" // Import as many different categories as you want to use.
|
||||||
@ -534,7 +534,7 @@ int main (int argc, const char * argv[]) {
|
|||||||
[mustang turnOn]; // Use methods from base Car class.
|
[mustang turnOn]; // Use methods from base Car class.
|
||||||
[mustang washWindows]; // Use methods from Car's Clean category.
|
[mustang washWindows]; // Use methods from Car's Clean category.
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Objective-C does not have protected method declarations but you can simulate them.
|
// Objective-C does not have protected method declarations but you can simulate them.
|
||||||
@ -548,7 +548,7 @@ int main (int argc, const char * argv[]) {
|
|||||||
//To use protected methods, import the category, then implement the methods:
|
//To use protected methods, import the category, then implement the methods:
|
||||||
#import "Car+Protected.h" // Remember, import in the @implementation file only.
|
#import "Car+Protected.h" // Remember, import in the @implementation file only.
|
||||||
|
|
||||||
@implementation Car
|
@implementation Car
|
||||||
|
|
||||||
- (void)lockCar {
|
- (void)lockCar {
|
||||||
NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
|
NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
|
||||||
@ -571,8 +571,8 @@ int main (int argc, const char * argv[]) {
|
|||||||
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
|
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
|
||||||
// @implementation filename: Shape.m
|
// @implementation filename: Shape.m
|
||||||
#import "Shape.h"
|
#import "Shape.h"
|
||||||
// Extensions live in the same file as the class @implementation.
|
// Extensions live in the same file as the class @implementation.
|
||||||
@interface Shape () // () after base class name declares an extension.
|
@interface Shape () // () after base class name declares an extension.
|
||||||
|
|
||||||
@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
|
@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
|
||||||
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
|
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
|
||||||
@ -580,7 +580,7 @@ int main (int argc, const char * argv[]) {
|
|||||||
|
|
||||||
@end
|
@end
|
||||||
// The main @implementation:
|
// The main @implementation:
|
||||||
@implementation Shape
|
@implementation Shape
|
||||||
|
|
||||||
@synthesize numOfSides = _numOfSides;
|
@synthesize numOfSides = _numOfSides;
|
||||||
|
|
||||||
@ -604,14 +604,14 @@ int main (int argc, const char * argv[]) {
|
|||||||
@property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
|
@property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
|
||||||
- (void)turnOnEngine; // all defined methods.
|
- (void)turnOnEngine; // all defined methods.
|
||||||
@end
|
@end
|
||||||
// Below is an example class implementing the protocol.
|
// Below is an example class implementing the protocol.
|
||||||
#import "CarUtilities.h" // Import the @protocol file.
|
#import "CarUtilities.h" // Import the @protocol file.
|
||||||
|
|
||||||
@interface Car : NSObject <CarUtilities> // Name of protocol goes inside <>
|
@interface Car : NSObject <CarUtilities> // Name of protocol goes inside <>
|
||||||
// You don't need the @property or method names here for CarUtilities. Only @implementation does.
|
// You don't need the @property or method names here for CarUtilities. Only @implementation does.
|
||||||
- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // You can use protocols as data too.
|
- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // You can use protocols as data too.
|
||||||
@end
|
@end
|
||||||
// The @implementation needs to implement the @properties and methods for the protocol.
|
// The @implementation needs to implement the @properties and methods for the protocol.
|
||||||
@implementation Car : NSObject <CarUtilities>
|
@implementation Car : NSObject <CarUtilities>
|
||||||
|
|
||||||
@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
|
@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
|
||||||
@ -620,14 +620,14 @@ int main (int argc, const char * argv[]) {
|
|||||||
_engineOn = YES; // how you implement a method, it just requires that you do implement it.
|
_engineOn = YES; // how you implement a method, it just requires that you do implement it.
|
||||||
}
|
}
|
||||||
// You may use a protocol as data as you know what methods and variables it has implemented.
|
// You may use a protocol as data as you know what methods and variables it has implemented.
|
||||||
- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
|
- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
|
||||||
[objectOfSomeKind engineOn]; // You have access to object variables
|
[objectOfSomeKind engineOn]; // You have access to object variables
|
||||||
[objectOfSomeKind turnOnEngine]; // and the methods inside.
|
[objectOfSomeKind turnOnEngine]; // and the methods inside.
|
||||||
[objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
|
[objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
|
||||||
}
|
}
|
||||||
|
|
||||||
@end
|
@end
|
||||||
// Instances of Car now have access to the protocol.
|
// Instances of Car now have access to the protocol.
|
||||||
Car *carInstance = [[Car alloc] init];
|
Car *carInstance = [[Car alloc] init];
|
||||||
[carInstance setEngineOn:NO];
|
[carInstance setEngineOn:NO];
|
||||||
[carInstance turnOnEngine];
|
[carInstance turnOnEngine];
|
||||||
@ -656,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
|
|||||||
// See the problem is that Sister relies on Brother, and Brother relies on Sister.
|
// See the problem is that Sister relies on Brother, and Brother relies on Sister.
|
||||||
#import "Sister.h"
|
#import "Sister.h"
|
||||||
|
|
||||||
@protocol Sister; // These lines stop the recursion, resolving the issue.
|
@protocol Sister; // These lines stop the recursion, resolving the issue.
|
||||||
|
|
||||||
@protocol Brother <NSObject>
|
@protocol Brother <NSObject>
|
||||||
|
|
||||||
- (void)beNiceToSister:(id <Sister>)sister;
|
- (void)beNiceToSister:(id <Sister>)sister;
|
||||||
|
|
||||||
@end
|
@end
|
||||||
@ -668,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
|
|||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Blocks
|
// Blocks
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Blocks are statements of code, just like a function, that are able to be used as data.
|
// Blocks are statements of code, just like a function, that are able to be used as data.
|
||||||
// Below is a simple block with an integer argument that returns the argument plus 4.
|
// Below is a simple block with an integer argument that returns the argument plus 4.
|
||||||
int (^addUp)(int n); // Declare a variable to store the block.
|
int (^addUp)(int n); // Declare a variable to store the block.
|
||||||
void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
|
void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
|
||||||
// Blocks have access to variables in the same scope. But the variables are readonly and the
|
// Blocks have access to variables in the same scope. But the variables are readonly and the
|
||||||
// value passed to the block is the value of the variable when the block is created.
|
// value passed to the block is the value of the variable when the block is created.
|
||||||
int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17.
|
int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17.
|
||||||
__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar.
|
__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar.
|
||||||
addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
|
addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
|
||||||
NSLog(@"You may have as many lines in a block as you would like.");
|
NSLog(@"You may have as many lines in a block as you would like.");
|
||||||
NSSet *blockSet; // Also, you can declare local variables.
|
NSSet *blockSet; // Also, you can declare local variables.
|
||||||
mutableVar = 32; // Assigning new value to __block variable.
|
mutableVar = 32; // Assigning new value to __block variable.
|
||||||
return n + outsideVar; // Return statements are optional.
|
return n + outsideVar; // Return statements are optional.
|
||||||
}
|
}
|
||||||
int addUp = add(10 + 16); // Calls block code with arguments.
|
int addUp = add(10 + 16); // Calls block code with arguments.
|
||||||
// Blocks are often used as arguments to functions to be called later, or for callbacks.
|
// Blocks are often used as arguments to functions to be called later, or for callbacks.
|
||||||
@implementation BlockExample : NSObject
|
@implementation BlockExample : NSObject
|
||||||
|
|
||||||
- (void)runBlock:(void (^)(NSString))block {
|
- (void)runBlock:(void (^)(NSString))block {
|
||||||
NSLog(@"Block argument returns nothing and takes in a NSString object.");
|
NSLog(@"Block argument returns nothing and takes in a NSString object.");
|
||||||
block(@"Argument given to block to execute."); // Calling block.
|
block(@"Argument given to block to execute."); // Calling block.
|
||||||
@ -697,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments.
|
|||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Memory Management
|
// Memory Management
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
/*
|
/*
|
||||||
For each object used in an application, memory must be allocated for that object. When the application
|
For each object used in an application, memory must be allocated for that object. When the application
|
||||||
is done using that object, memory must be deallocated to ensure application efficiency.
|
is done using that object, memory must be deallocated to ensure application efficiency.
|
||||||
Objective-C does not use garbage collection and instead uses reference counting. As long as
|
Objective-C does not use garbage collection and instead uses reference counting. As long as
|
||||||
there is at least one reference to an object (also called "owning" an object), then the object
|
there is at least one reference to an object (also called "owning" an object), then the object
|
||||||
will be available to use (known as "ownership").
|
will be available to use (known as "ownership").
|
||||||
|
|
||||||
When an instance owns an object, its reference counter is increments by one. When the
|
When an instance owns an object, its reference counter is increments by one. When the
|
||||||
object is released, the reference counter decrements by one. When reference count is zero,
|
object is released, the reference counter decrements by one. When reference count is zero,
|
||||||
the object is removed from memory.
|
the object is removed from memory.
|
||||||
|
|
||||||
With all object interactions, follow the pattern of:
|
With all object interactions, follow the pattern of:
|
||||||
(1) create the object, (2) use the object, (3) then free the object from memory.
|
(1) create the object, (2) use the object, (3) then free the object from memory.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object
|
MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object
|
||||||
@ -724,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still
|
|||||||
|
|
||||||
// Automatic Reference Counting (ARC)
|
// Automatic Reference Counting (ARC)
|
||||||
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
|
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
|
||||||
// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
|
// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
|
||||||
// you must not use retain, relase, or autorelease
|
// you must not use retain, relase, or autorelease
|
||||||
MyClass *arcMyClass = [[MyClass alloc] init];
|
MyClass *arcMyClass = [[MyClass alloc] init];
|
||||||
// ... code using arcMyClass
|
// ... code using arcMyClass
|
||||||
// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
|
// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
|
||||||
// there is no need. It will insert this release statement for you
|
// there is no need. It will insert this release statement for you
|
||||||
|
|
||||||
// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
|
// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
|
||||||
|
@ -34,13 +34,13 @@ For a source file you can use "ocamlc -i /path/to/file.ml" command
|
|||||||
to print all names and type signatures.
|
to print all names and type signatures.
|
||||||
|
|
||||||
```
|
```
|
||||||
$ cat sigtest.ml
|
$ cat sigtest.ml
|
||||||
let inc x = x + 1
|
let inc x = x + 1
|
||||||
let add x y = x + y
|
let add x y = x + y
|
||||||
|
|
||||||
let a = 1
|
let a = 1
|
||||||
|
|
||||||
$ ocamlc -i ./sigtest.ml
|
$ ocamlc -i ./sigtest.ml
|
||||||
val inc : int -> int
|
val inc : int -> int
|
||||||
val add : int -> int -> int
|
val add : int -> int -> int
|
||||||
val a : int
|
val a : int
|
||||||
@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;;
|
|||||||
let sqr2 = sqr (-2) ;;
|
let sqr2 = sqr (-2) ;;
|
||||||
|
|
||||||
(* Every function must have at least one argument.
|
(* Every function must have at least one argument.
|
||||||
Since some funcions naturally don't take any arguments, there's
|
Since some funcions naturally don't take any arguments, there's
|
||||||
"unit" type for it that has the only one value written as "()" *)
|
"unit" type for it that has the only one value written as "()" *)
|
||||||
let print_hello () = print_endline "hello world" ;;
|
let print_hello () = print_endline "hello world" ;;
|
||||||
|
|
||||||
@ -301,7 +301,7 @@ let l = IntList (1, EmptyList) ;;
|
|||||||
(* Pattern matching is somewhat similar to switch statement in imperative
|
(* Pattern matching is somewhat similar to switch statement in imperative
|
||||||
languages, but offers a lot more expressive power.
|
languages, but offers a lot more expressive power.
|
||||||
|
|
||||||
Even though it may look complicated, it really boils down to matching
|
Even though it may look complicated, it really boils down to matching
|
||||||
an argument against an exact value, a predicate, or a type constructor.
|
an argument against an exact value, a predicate, or a type constructor.
|
||||||
The type system is what makes it so powerful. *)
|
The type system is what makes it so powerful. *)
|
||||||
|
|
||||||
@ -320,7 +320,7 @@ let is_one = function
|
|||||||
;;
|
;;
|
||||||
|
|
||||||
(* Matching predicates, aka "guarded pattern matching". *)
|
(* Matching predicates, aka "guarded pattern matching". *)
|
||||||
let abs x =
|
let abs x =
|
||||||
match x with
|
match x with
|
||||||
| x when x < 0 -> -x
|
| x when x < 0 -> -x
|
||||||
| _ -> x
|
| _ -> x
|
||||||
|
@ -7,11 +7,11 @@ contributors:
|
|||||||
- ["Nami-Doc", "http://github.com/Nami-Doc"]
|
- ["Nami-Doc", "http://github.com/Nami-Doc"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Perl 6 is a highly capable, feature-rich programming language made for at
|
Perl 6 is a highly capable, feature-rich programming language made for at
|
||||||
least the next hundred years.
|
least the next hundred years.
|
||||||
|
|
||||||
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
|
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
|
||||||
the JVM and [the MoarVM](http://moarvm.com) and
|
the JVM and [the MoarVM](http://moarvm.com) and
|
||||||
[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/),
|
[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/),
|
||||||
[the Parrot VM](http://parrot.org/).
|
[the Parrot VM](http://parrot.org/).
|
||||||
|
|
||||||
@ -143,7 +143,7 @@ sub with-mandatory-named(:$str!) {
|
|||||||
say "$str !";
|
say "$str !";
|
||||||
}
|
}
|
||||||
with-mandatory-named(str => "My String"); #=> My String !
|
with-mandatory-named(str => "My String"); #=> My String !
|
||||||
with-mandatory-named; # run time error: "Required named parameter not passed"
|
with-mandatory-named; # run time error: "Required named parameter not passed"
|
||||||
with-mandatory-named(3); # run time error: "Too many positional parameters passed"
|
with-mandatory-named(3); # run time error: "Too many positional parameters passed"
|
||||||
|
|
||||||
## If a sub takes a named boolean argument ...
|
## If a sub takes a named boolean argument ...
|
||||||
@ -290,7 +290,7 @@ for @array -> $variable {
|
|||||||
# That means you can use `when` in a `for` just like you were in a `given`.
|
# That means you can use `when` in a `for` just like you were in a `given`.
|
||||||
for @array {
|
for @array {
|
||||||
say "I've got $_";
|
say "I've got $_";
|
||||||
|
|
||||||
.say; # This is also allowed.
|
.say; # This is also allowed.
|
||||||
# A dot call with no "topic" (receiver) is sent to `$_` by default
|
# A dot call with no "topic" (receiver) is sent to `$_` by default
|
||||||
$_.say; # the above and this are equivalent.
|
$_.say; # the above and this are equivalent.
|
||||||
@ -378,8 +378,8 @@ say join(' ', @array[15..*]); #=> 15 16 17 18 19
|
|||||||
# which is equivalent to:
|
# which is equivalent to:
|
||||||
say join(' ', @array[-> $n { 15..$n }]);
|
say join(' ', @array[-> $n { 15..$n }]);
|
||||||
|
|
||||||
# You can use that in most places you'd expect, even assigning to an array
|
# You can use that in most places you'd expect, even assigning to an array
|
||||||
my @numbers = ^20;
|
my @numbers = ^20;
|
||||||
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
|
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
|
||||||
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
|
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
|
||||||
# only the 15 needed values will be calculated.
|
# only the 15 needed values will be calculated.
|
||||||
@ -634,14 +634,14 @@ class A {
|
|||||||
method get-value {
|
method get-value {
|
||||||
$.field + $!private-field;
|
$.field + $!private-field;
|
||||||
}
|
}
|
||||||
|
|
||||||
method set-value($n) {
|
method set-value($n) {
|
||||||
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
|
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
|
||||||
$!field = $n; # This works, because `$!` is always mutable.
|
$!field = $n; # This works, because `$!` is always mutable.
|
||||||
|
|
||||||
$.other-field = 5; # This works, because `$.other-field` is `rw`.
|
$.other-field = 5; # This works, because `$.other-field` is `rw`.
|
||||||
}
|
}
|
||||||
|
|
||||||
method !private-method {
|
method !private-method {
|
||||||
say "This method is private to the class !";
|
say "This method is private to the class !";
|
||||||
}
|
}
|
||||||
@ -660,19 +660,19 @@ $a.other-field = 10; # This, however, works, because the public field
|
|||||||
|
|
||||||
class A {
|
class A {
|
||||||
has $.val;
|
has $.val;
|
||||||
|
|
||||||
submethod not-inherited {
|
submethod not-inherited {
|
||||||
say "This method won't be available on B.";
|
say "This method won't be available on B.";
|
||||||
say "This is most useful for BUILD, which we'll see later";
|
say "This is most useful for BUILD, which we'll see later";
|
||||||
}
|
}
|
||||||
|
|
||||||
method bar { $.val * 5 }
|
method bar { $.val * 5 }
|
||||||
}
|
}
|
||||||
class B is A { # inheritance uses `is`
|
class B is A { # inheritance uses `is`
|
||||||
method foo {
|
method foo {
|
||||||
say $.val;
|
say $.val;
|
||||||
}
|
}
|
||||||
|
|
||||||
method bar { $.val * 10 } # this shadows A's `bar`
|
method bar { $.val * 10 } # this shadows A's `bar`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -699,20 +699,20 @@ role PrintableVal {
|
|||||||
# you "import" a mixin (a "role") with "does":
|
# you "import" a mixin (a "role") with "does":
|
||||||
class Item does PrintableVal {
|
class Item does PrintableVal {
|
||||||
has $.val;
|
has $.val;
|
||||||
|
|
||||||
# When `does`-ed, a `role` literally "mixes in" the class:
|
# When `does`-ed, a `role` literally "mixes in" the class:
|
||||||
# the methods and fields are put together, which means a class can access
|
# the methods and fields are put together, which means a class can access
|
||||||
# the private fields/methods of its roles (but not the inverse !):
|
# the private fields/methods of its roles (but not the inverse !):
|
||||||
method access {
|
method access {
|
||||||
say $!counter++;
|
say $!counter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
# However, this:
|
# However, this:
|
||||||
# method print {}
|
# method print {}
|
||||||
# is ONLY valid when `print` isn't a `multi` with the same dispatch.
|
# is ONLY valid when `print` isn't a `multi` with the same dispatch.
|
||||||
# (this means a parent class can shadow a child class's `multi print() {}`,
|
# (this means a parent class can shadow a child class's `multi print() {}`,
|
||||||
# but it's an error if a role does)
|
# but it's an error if a role does)
|
||||||
|
|
||||||
# NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
|
# NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
|
||||||
# will be shadowed, since the compiler will consider `ROLE` to be a class.
|
# will be shadowed, since the compiler will consider `ROLE` to be a class.
|
||||||
}
|
}
|
||||||
@ -812,7 +812,7 @@ module Foo::Bar {
|
|||||||
say "Can't access me from outside, I'm my !";
|
say "Can't access me from outside, I'm my !";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
say ++$n; # lexically-scoped variables are still available
|
say ++$n; # lexically-scoped variables are still available
|
||||||
}
|
}
|
||||||
say $Foo::Bar::n; #=> 1
|
say $Foo::Bar::n; #=> 1
|
||||||
@ -1075,8 +1075,8 @@ say [//] Nil, Any, False, 1, 5; #=> False
|
|||||||
|
|
||||||
|
|
||||||
# Default value examples:
|
# Default value examples:
|
||||||
say [*] (); #=> 1
|
say [*] (); #=> 1
|
||||||
say [+] (); #=> 0
|
say [+] (); #=> 0
|
||||||
# meaningless values, since N*1=N and N+0=N.
|
# meaningless values, since N*1=N and N+0=N.
|
||||||
say [//]; #=> (Any)
|
say [//]; #=> (Any)
|
||||||
# There's no "default value" for `//`.
|
# There's no "default value" for `//`.
|
||||||
@ -1335,7 +1335,7 @@ sub MAIN($name) { say "Hello, $name !" }
|
|||||||
# This produces:
|
# This produces:
|
||||||
# $ perl6 cli.pl
|
# $ perl6 cli.pl
|
||||||
# Usage:
|
# Usage:
|
||||||
# t.pl <name>
|
# t.pl <name>
|
||||||
|
|
||||||
# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
|
# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
|
||||||
# (using a "Bool" for the named argument so that we can do `--replace`
|
# (using a "Bool" for the named argument so that we can do `--replace`
|
||||||
@ -1348,7 +1348,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
|
|||||||
# This produces:
|
# This produces:
|
||||||
# $ perl 6 cli.pl
|
# $ perl 6 cli.pl
|
||||||
# Usage:
|
# Usage:
|
||||||
# t.pl [--replace] add <key> <value>
|
# t.pl [--replace] add <key> <value>
|
||||||
# t.pl remove <key>
|
# t.pl remove <key>
|
||||||
# t.pl [--as=<Str>] import (File)
|
# t.pl [--as=<Str>] import (File)
|
||||||
# As you can see, this is *very* powerful.
|
# As you can see, this is *very* powerful.
|
||||||
@ -1400,7 +1400,7 @@ for <well met young hero we shall meet later> {
|
|||||||
# (explained in details below).
|
# (explained in details below).
|
||||||
.say
|
.say
|
||||||
}
|
}
|
||||||
|
|
||||||
if rand == 0 ff rand == 1 { # compare variables other than `$_`
|
if rand == 0 ff rand == 1 { # compare variables other than `$_`
|
||||||
say "This ... probably will never run ...";
|
say "This ... probably will never run ...";
|
||||||
}
|
}
|
||||||
|
@ -515,7 +515,7 @@ class MyClass
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Class constants can always be accessed statically
|
// Class constants can always be accessed statically
|
||||||
echo MyClass::MY_CONST; // Outputs 'value';
|
echo MyClass::MY_CONST; // Outputs 'value';
|
||||||
|
|
||||||
echo MyClass::$staticVar; // Outputs 'static';
|
echo MyClass::$staticVar; // Outputs 'static';
|
||||||
|
@ -70,12 +70,12 @@ true && (9 >= 19 || 1 < 2) -- true
|
|||||||
|
|
||||||
-- Safe access return Maybe a
|
-- Safe access return Maybe a
|
||||||
head [1,2,3] -- Just (1)
|
head [1,2,3] -- Just (1)
|
||||||
tail [3,2,1] -- Just ([2,1])
|
tail [3,2,1] -- Just ([2,1])
|
||||||
init [1,2,3] -- Just ([1,2])
|
init [1,2,3] -- Just ([1,2])
|
||||||
last [3,2,1] -- Just (1)
|
last [3,2,1] -- Just (1)
|
||||||
-- Random access - indexing
|
-- Random access - indexing
|
||||||
[3,4,5,6,7] !! 2 -- Just (5)
|
[3,4,5,6,7] !! 2 -- Just (5)
|
||||||
-- Range
|
-- Range
|
||||||
1..5 -- [1,2,3,4,5]
|
1..5 -- [1,2,3,4,5]
|
||||||
length [2,2,2] -- 3
|
length [2,2,2] -- 3
|
||||||
drop 3 [5,4,3,2,1] -- [2,1]
|
drop 3 [5,4,3,2,1] -- [2,1]
|
||||||
@ -129,10 +129,10 @@ first :: [Number] -> Number
|
|||||||
first (x:_) = x
|
first (x:_) = x
|
||||||
first [3,4,5] -- 3
|
first [3,4,5] -- 3
|
||||||
second :: [Number] -> Number
|
second :: [Number] -> Number
|
||||||
second (_:y:_) = y
|
second (_:y:_) = y
|
||||||
second [3,4,5] -- 4
|
second [3,4,5] -- 4
|
||||||
sumTwo :: [Number] -> [Number]
|
sumTwo :: [Number] -> [Number]
|
||||||
sumTwo (x:y:rest) = (x+y) : rest
|
sumTwo (x:y:rest) = (x+y) : rest
|
||||||
sumTwo [2,3,4,5,6] -- [5,4,5,6]
|
sumTwo [2,3,4,5,6] -- [5,4,5,6]
|
||||||
|
|
||||||
-- sumTwo doesn't handle when the array is empty or just have one
|
-- sumTwo doesn't handle when the array is empty or just have one
|
||||||
@ -161,7 +161,7 @@ ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
|
|||||||
|
|
||||||
-- Lambda expressions
|
-- Lambda expressions
|
||||||
(\x -> x*x) 3 -- 9
|
(\x -> x*x) 3 -- 9
|
||||||
(\x y -> x*x + y*y) 4 5 -- 41
|
(\x y -> x*x + y*y) 4 5 -- 41
|
||||||
sqr = \x -> x*x
|
sqr = \x -> x*x
|
||||||
|
|
||||||
-- Currying
|
-- Currying
|
||||||
@ -187,7 +187,7 @@ foldr (+) 0 (1..10) -- 55
|
|||||||
sum (1..10) -- 55
|
sum (1..10) -- 55
|
||||||
product (1..10) -- 3628800
|
product (1..10) -- 3628800
|
||||||
|
|
||||||
-- Testing with predicate
|
-- Testing with predicate
|
||||||
any even [1,2,3] -- true
|
any even [1,2,3] -- true
|
||||||
all even [1,2,3] -- false
|
all even [1,2,3] -- false
|
||||||
|
|
||||||
|
@ -96,7 +96,7 @@ False or True #=> True
|
|||||||
1 < 2 < 3 # => True
|
1 < 2 < 3 # => True
|
||||||
2 < 3 < 2 # => False
|
2 < 3 < 2 # => False
|
||||||
|
|
||||||
# (is vs. ==) is checks if two variable refer to the same object, but == checks
|
# (is vs. ==) is checks if two variable refer to the same object, but == checks
|
||||||
# if the objects pointed to have the same values.
|
# if the objects pointed to have the same values.
|
||||||
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
|
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
|
||||||
b = a # Point b at what a is pointing to
|
b = a # Point b at what a is pointing to
|
||||||
@ -256,8 +256,8 @@ empty_dict = {}
|
|||||||
# Here is a prefilled dictionary
|
# Here is a prefilled dictionary
|
||||||
filled_dict = {"one": 1, "two": 2, "three": 3}
|
filled_dict = {"one": 1, "two": 2, "three": 3}
|
||||||
|
|
||||||
# Note keys for dictionaries have to be immutable types. This is to ensure that
|
# Note keys for dictionaries have to be immutable types. This is to ensure that
|
||||||
# the key can be converted to a constant hash value for quick look-ups.
|
# the key can be converted to a constant hash value for quick look-ups.
|
||||||
# Immutable types include ints, floats, strings, tuples.
|
# Immutable types include ints, floats, strings, tuples.
|
||||||
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
|
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
|
||||||
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
|
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
|
||||||
@ -423,7 +423,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks
|
|||||||
print("All good!") # Runs only if the code in try raises no exceptions
|
print("All good!") # Runs only if the code in try raises no exceptions
|
||||||
finally: # Execute under all circumstances
|
finally: # Execute under all circumstances
|
||||||
print("We can clean up resources here")
|
print("We can clean up resources here")
|
||||||
|
|
||||||
# Instead of try/finally to cleanup resources you can use a with statement
|
# Instead of try/finally to cleanup resources you can use a with statement
|
||||||
with open("myfile.txt") as f:
|
with open("myfile.txt") as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
|
@ -36,8 +36,8 @@ head(rivers) # peek at the data set
|
|||||||
length(rivers) # how many rivers were measured?
|
length(rivers) # how many rivers were measured?
|
||||||
# 141
|
# 141
|
||||||
summary(rivers) # what are some summary statistics?
|
summary(rivers) # what are some summary statistics?
|
||||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||||
# 135.0 310.0 425.0 591.2 680.0 3710.0
|
# 135.0 310.0 425.0 591.2 680.0 3710.0
|
||||||
|
|
||||||
# make a stem-and-leaf plot (a histogram-like data visualization)
|
# make a stem-and-leaf plot (a histogram-like data visualization)
|
||||||
stem(rivers)
|
stem(rivers)
|
||||||
@ -54,14 +54,14 @@ stem(rivers)
|
|||||||
# 14 | 56
|
# 14 | 56
|
||||||
# 16 | 7
|
# 16 | 7
|
||||||
# 18 | 9
|
# 18 | 9
|
||||||
# 20 |
|
# 20 |
|
||||||
# 22 | 25
|
# 22 | 25
|
||||||
# 24 | 3
|
# 24 | 3
|
||||||
# 26 |
|
# 26 |
|
||||||
# 28 |
|
# 28 |
|
||||||
# 30 |
|
# 30 |
|
||||||
# 32 |
|
# 32 |
|
||||||
# 34 |
|
# 34 |
|
||||||
# 36 | 1
|
# 36 | 1
|
||||||
|
|
||||||
stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
|
stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
|
||||||
@ -70,7 +70,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
|
|||||||
# The decimal point is 1 digit(s) to the left of the |
|
# The decimal point is 1 digit(s) to the left of the |
|
||||||
#
|
#
|
||||||
# 48 | 1
|
# 48 | 1
|
||||||
# 50 |
|
# 50 |
|
||||||
# 52 | 15578
|
# 52 | 15578
|
||||||
# 54 | 44571222466689
|
# 54 | 44571222466689
|
||||||
# 56 | 023334677000124455789
|
# 56 | 023334677000124455789
|
||||||
@ -85,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
|
|||||||
# 74 | 84
|
# 74 | 84
|
||||||
# 76 | 56
|
# 76 | 56
|
||||||
# 78 | 4
|
# 78 | 4
|
||||||
# 80 |
|
# 80 |
|
||||||
# 82 | 2
|
# 82 | 2
|
||||||
|
|
||||||
# make a histogram:
|
# make a histogram:
|
||||||
@ -108,7 +108,7 @@ sort(discoveries)
|
|||||||
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
|
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
|
||||||
|
|
||||||
stem(discoveries, scale=2)
|
stem(discoveries, scale=2)
|
||||||
#
|
#
|
||||||
# The decimal point is at the |
|
# The decimal point is at the |
|
||||||
#
|
#
|
||||||
# 0 | 000000000
|
# 0 | 000000000
|
||||||
@ -122,14 +122,14 @@ stem(discoveries, scale=2)
|
|||||||
# 8 | 0
|
# 8 | 0
|
||||||
# 9 | 0
|
# 9 | 0
|
||||||
# 10 | 0
|
# 10 | 0
|
||||||
# 11 |
|
# 11 |
|
||||||
# 12 | 0
|
# 12 | 0
|
||||||
|
|
||||||
max(discoveries)
|
max(discoveries)
|
||||||
# 12
|
# 12
|
||||||
summary(discoveries)
|
summary(discoveries)
|
||||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||||
# 0.0 2.0 3.0 3.1 4.0 12.0
|
# 0.0 2.0 3.0 3.1 4.0 12.0
|
||||||
|
|
||||||
# Roll a die a few times
|
# Roll a die a few times
|
||||||
round(runif(7, min=.5, max=6.5))
|
round(runif(7, min=.5, max=6.5))
|
||||||
@ -262,7 +262,7 @@ class(NULL) # NULL
|
|||||||
parakeet = c("beak", "feathers", "wings", "eyes")
|
parakeet = c("beak", "feathers", "wings", "eyes")
|
||||||
parakeet
|
parakeet
|
||||||
# =>
|
# =>
|
||||||
# [1] "beak" "feathers" "wings" "eyes"
|
# [1] "beak" "feathers" "wings" "eyes"
|
||||||
parakeet <- NULL
|
parakeet <- NULL
|
||||||
parakeet
|
parakeet
|
||||||
# =>
|
# =>
|
||||||
@ -279,7 +279,7 @@ as.numeric("Bilbo")
|
|||||||
# =>
|
# =>
|
||||||
# [1] NA
|
# [1] NA
|
||||||
# Warning message:
|
# Warning message:
|
||||||
# NAs introduced by coercion
|
# NAs introduced by coercion
|
||||||
|
|
||||||
# Also note: those were just the basic data types
|
# Also note: those were just the basic data types
|
||||||
# There are many more data types, such as for dates, time series, etc.
|
# There are many more data types, such as for dates, time series, etc.
|
||||||
@ -419,10 +419,10 @@ mat %*% t(mat)
|
|||||||
mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
|
mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
|
||||||
mat2
|
mat2
|
||||||
# =>
|
# =>
|
||||||
# [,1] [,2]
|
# [,1] [,2]
|
||||||
# [1,] "1" "dog"
|
# [1,] "1" "dog"
|
||||||
# [2,] "2" "cat"
|
# [2,] "2" "cat"
|
||||||
# [3,] "3" "bird"
|
# [3,] "3" "bird"
|
||||||
# [4,] "4" "dog"
|
# [4,] "4" "dog"
|
||||||
class(mat2) # matrix
|
class(mat2) # matrix
|
||||||
# Again, note what happened!
|
# Again, note what happened!
|
||||||
|
@ -285,7 +285,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
|
|||||||
(= 3 3.0) ; => #t
|
(= 3 3.0) ; => #t
|
||||||
(= 2 1) ; => #f
|
(= 2 1) ; => #f
|
||||||
|
|
||||||
;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
|
;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
|
||||||
;; #f otherwise.
|
;; #f otherwise.
|
||||||
;; In other words, it's a simple pointer comparison.
|
;; In other words, it's a simple pointer comparison.
|
||||||
(eq? '() '()) ; => #t, since there exists only one empty list in memory
|
(eq? '() '()) ; => #t, since there exists only one empty list in memory
|
||||||
@ -320,7 +320,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
|
|||||||
(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
|
(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
|
||||||
|
|
||||||
;; `equal?' supports the comparison of the following datatypes:
|
;; `equal?' supports the comparison of the following datatypes:
|
||||||
;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
|
;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
|
||||||
;; hash tables, and inspectable structures.
|
;; hash tables, and inspectable structures.
|
||||||
;; for other datatypes, `equal?' and `eqv?' return the same result.
|
;; for other datatypes, `equal?' and `eqv?' return the same result.
|
||||||
(equal? 3 3.0) ; => #f
|
(equal? 3 3.0) ; => #f
|
||||||
|
@ -8,31 +8,31 @@ contributors:
|
|||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
|
Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
|
||||||
It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language.
|
It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language.
|
||||||
|
|
||||||
Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in.
|
Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in.
|
||||||
Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
|
Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
|
||||||
Red/System, covers the more basic needs of programming like C can, being closer to the metal.
|
Red/System, covers the more basic needs of programming like C can, being closer to the metal.
|
||||||
|
|
||||||
Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
|
Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
|
||||||
from the metal to the meta without the aid of other stack tools.
|
from the metal to the meta without the aid of other stack tools.
|
||||||
Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
|
Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
|
||||||
from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB.
|
from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB.
|
||||||
|
|
||||||
Ready to learn your first Red?
|
Ready to learn your first Red?
|
||||||
|
|
||||||
```
|
```
|
||||||
All text before the header will be treated as comment, as long as you avoid using the
|
All text before the header will be treated as comment, as long as you avoid using the
|
||||||
word "red" starting with a capital "R" in this pre-header text. This is a temporary
|
word "red" starting with a capital "R" in this pre-header text. This is a temporary
|
||||||
shortcoming of the used lexer but most of the time you start your script or program
|
shortcoming of the used lexer but most of the time you start your script or program
|
||||||
with the header itself.
|
with the header itself.
|
||||||
The header of a red script is the capitalized word "red" followed by a
|
The header of a red script is the capitalized word "red" followed by a
|
||||||
whitespace character followed by a block of square brackets [].
|
whitespace character followed by a block of square brackets [].
|
||||||
The block of brackets can be filled with useful information about this script or
|
The block of brackets can be filled with useful information about this script or
|
||||||
program: the author's name, the filename, the version, the license, a summary of
|
program: the author's name, the filename, the version, the license, a summary of
|
||||||
what the program does or any other files it needs.
|
what the program does or any other files it needs.
|
||||||
The red/System header is just like the red header, only saying "red/System" and
|
The red/System header is just like the red header, only saying "red/System" and
|
||||||
not "red".
|
not "red".
|
||||||
|
|
||||||
Red []
|
Red []
|
||||||
@ -49,21 +49,21 @@ comment {
|
|||||||
; Your program's entry point is the first executable code that is found
|
; Your program's entry point is the first executable code that is found
|
||||||
; no need to restrict this to a 'main' function.
|
; no need to restrict this to a 'main' function.
|
||||||
|
|
||||||
; Valid variable names start with a letter and can contain numbers,
|
; Valid variable names start with a letter and can contain numbers,
|
||||||
; variables containing only capital A thru F and numbers and ending with 'h' are
|
; variables containing only capital A thru F and numbers and ending with 'h' are
|
||||||
; forbidden, because that is how hexadecimal numbers are expressed in Red and
|
; forbidden, because that is how hexadecimal numbers are expressed in Red and
|
||||||
; Red/System.
|
; Red/System.
|
||||||
|
|
||||||
; assign a value to a variable using a colon ":"
|
; assign a value to a variable using a colon ":"
|
||||||
my-name: "Red"
|
my-name: "Red"
|
||||||
reason-for-using-the-colon: {Assigning values using the colon makes
|
reason-for-using-the-colon: {Assigning values using the colon makes
|
||||||
the equality sign "=" exclusively usable for comparisons purposes,
|
the equality sign "=" exclusively usable for comparisons purposes,
|
||||||
exactly what "=" was intended for in the first place!
|
exactly what "=" was intended for in the first place!
|
||||||
Remember this y = x + 1 and x = 1 => y = 2 stuff from school?
|
Remember this y = x + 1 and x = 1 => y = 2 stuff from school?
|
||||||
}
|
}
|
||||||
is-this-name-valid?: true
|
is-this-name-valid?: true
|
||||||
|
|
||||||
; print output using print, or prin for printing without a newline or linefeed at the
|
; print output using print, or prin for printing without a newline or linefeed at the
|
||||||
; end of the printed text.
|
; end of the printed text.
|
||||||
|
|
||||||
prin " My name is " print my-name
|
prin " My name is " print my-name
|
||||||
@ -77,20 +77,20 @@ My name is Red
|
|||||||
;
|
;
|
||||||
; Datatypes
|
; Datatypes
|
||||||
;
|
;
|
||||||
; If you know Rebol, you probably have noticed it has lots of datatypes. Red
|
; If you know Rebol, you probably have noticed it has lots of datatypes. Red
|
||||||
; does not have yet all those types, but as Red want to be close to Rebol it
|
; does not have yet all those types, but as Red want to be close to Rebol it
|
||||||
; will have a lot of datatypes.
|
; will have a lot of datatypes.
|
||||||
; You can recognize types by the exclamation sign at the end. But beware
|
; You can recognize types by the exclamation sign at the end. But beware
|
||||||
; names ending with an exclamation sign are allowed.
|
; names ending with an exclamation sign are allowed.
|
||||||
; Some of the available types are integer! string! block!
|
; Some of the available types are integer! string! block!
|
||||||
|
|
||||||
; Declaring variables before using them?
|
; Declaring variables before using them?
|
||||||
; Red knows by itself what variable is best to use for the data you want to use it
|
; Red knows by itself what variable is best to use for the data you want to use it
|
||||||
; for.
|
; for.
|
||||||
; A variable declaration is not always necessary.
|
; A variable declaration is not always necessary.
|
||||||
; It is considered good coding practise to declare your variables,
|
; It is considered good coding practise to declare your variables,
|
||||||
; but it is not forced upon you by Red.
|
; but it is not forced upon you by Red.
|
||||||
; You can declare a variable and specify its type. a variable's type determines its
|
; You can declare a variable and specify its type. a variable's type determines its
|
||||||
; size in bytes.
|
; size in bytes.
|
||||||
|
|
||||||
; Variables of integer! type are usually 4 bytes or 32 bits
|
; Variables of integer! type are usually 4 bytes or 32 bits
|
||||||
@ -101,7 +101,7 @@ my-integer: 0
|
|||||||
type? my-integer
|
type? my-integer
|
||||||
integer!
|
integer!
|
||||||
|
|
||||||
; A variable can be initialized using another variable that gets initialized
|
; A variable can be initialized using another variable that gets initialized
|
||||||
; at the same time.
|
; at the same time.
|
||||||
i2: 1 + i1: 1
|
i2: 1 + i1: 1
|
||||||
|
|
||||||
@ -111,9 +111,9 @@ i2 - i1 ; result 1
|
|||||||
i2 * i1 ; result 2
|
i2 * i1 ; result 2
|
||||||
i1 / i2 ; result 0 (0.5, but truncated towards 0)
|
i1 / i2 ; result 0 (0.5, but truncated towards 0)
|
||||||
|
|
||||||
; Comparison operators are probably familiar, and unlike in other languages you
|
; Comparison operators are probably familiar, and unlike in other languages you
|
||||||
; only need a single '=' sign for comparison.
|
; only need a single '=' sign for comparison.
|
||||||
; There is a boolean like type in Red. It has values true and false, but also the
|
; There is a boolean like type in Red. It has values true and false, but also the
|
||||||
; values on/off or yes/no can be used
|
; values on/off or yes/no can be used
|
||||||
|
|
||||||
3 = 2 ; result false
|
3 = 2 ; result false
|
||||||
@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0)
|
|||||||
|
|
||||||
;
|
;
|
||||||
; Control Structures
|
; Control Structures
|
||||||
;
|
;
|
||||||
; if
|
; if
|
||||||
; Evaluate a block of code if a given condition is true. IF does not return any value,
|
; Evaluate a block of code if a given condition is true. IF does not return any value,
|
||||||
; so cannot be used in an expression.
|
; so cannot be used in an expression.
|
||||||
if a < 0 [print "a is negative"]
|
if a < 0 [print "a is negative"]
|
||||||
|
|
||||||
; either
|
; either
|
||||||
; Evaluate a block of code if a given condition is true, else evaluate an alternative
|
; Evaluate a block of code if a given condition is true, else evaluate an alternative
|
||||||
; block of code. If the last expressions in both blocks have the same type, EITHER can
|
; block of code. If the last expressions in both blocks have the same type, EITHER can
|
||||||
; be used inside an expression.
|
; be used inside an expression.
|
||||||
either a < 0 [
|
either a < 0 [
|
||||||
either a = 0 [
|
either a = 0 [
|
||||||
@ -147,7 +147,7 @@ either a < 0 [
|
|||||||
|
|
||||||
print ["a is " msg lf]
|
print ["a is " msg lf]
|
||||||
|
|
||||||
; There is an alternative way to write this
|
; There is an alternative way to write this
|
||||||
; (Which is allowed because all code paths return a value of the same type):
|
; (Which is allowed because all code paths return a value of the same type):
|
||||||
|
|
||||||
msg: either a < 0 [
|
msg: either a < 0 [
|
||||||
@ -162,7 +162,7 @@ msg: either a < 0 [
|
|||||||
print ["a is " msg lf]
|
print ["a is " msg lf]
|
||||||
|
|
||||||
; until
|
; until
|
||||||
; Loop over a block of code until the condition at end of block, is met.
|
; Loop over a block of code until the condition at end of block, is met.
|
||||||
; UNTIL does not return any value, so it cannot be used in an expression.
|
; UNTIL does not return any value, so it cannot be used in an expression.
|
||||||
c: 5
|
c: 5
|
||||||
until [
|
until [
|
||||||
@ -172,11 +172,11 @@ until [
|
|||||||
]
|
]
|
||||||
; will output:
|
; will output:
|
||||||
ooooo
|
ooooo
|
||||||
; Note that the loop will always be evaluated at least once, even if the condition is
|
; Note that the loop will always be evaluated at least once, even if the condition is
|
||||||
; not met from the beginning.
|
; not met from the beginning.
|
||||||
|
|
||||||
; while
|
; while
|
||||||
; While a given condition is met, evaluate a block of code.
|
; While a given condition is met, evaluate a block of code.
|
||||||
; WHILE does not return any value, so it cannot be used in an expression.
|
; WHILE does not return any value, so it cannot be used in an expression.
|
||||||
c: 5
|
c: 5
|
||||||
while [c > 0][
|
while [c > 0][
|
||||||
@ -206,7 +206,7 @@ print twice b ; will output 6.
|
|||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
|
The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
|
||||||
|
|
||||||
The source can be found on [github](https://github.com/red/red).
|
The source can be found on [github](https://github.com/red/red).
|
||||||
|
|
||||||
@ -218,4 +218,4 @@ Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/r
|
|||||||
|
|
||||||
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
|
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
|
||||||
|
|
||||||
You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
|
You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
|
||||||
|
@ -6,20 +6,20 @@ filename: learnrust.rs
|
|||||||
---
|
---
|
||||||
|
|
||||||
Rust is a programming language developed by Mozilla Research.
|
Rust is a programming language developed by Mozilla Research.
|
||||||
Rust combines low-level control over performance with high-level convenience and
|
Rust combines low-level control over performance with high-level convenience and
|
||||||
safety guarantees.
|
safety guarantees.
|
||||||
|
|
||||||
It achieves these goals without requiring a garbage collector or runtime, making
|
It achieves these goals without requiring a garbage collector or runtime, making
|
||||||
it possible to use Rust libraries as a "drop-in replacement" for C.
|
it possible to use Rust libraries as a "drop-in replacement" for C.
|
||||||
|
|
||||||
Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
|
Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
|
||||||
moved so quickly that until recently the use of stable releases was discouraged
|
moved so quickly that until recently the use of stable releases was discouraged
|
||||||
and instead the general advice was to use nightly builds.
|
and instead the general advice was to use nightly builds.
|
||||||
|
|
||||||
On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
|
On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
|
||||||
compatibility. Improvements to compile times and other aspects of the compiler are
|
compatibility. Improvements to compile times and other aspects of the compiler are
|
||||||
currently available in the nightly builds. Rust has adopted a train-based release
|
currently available in the nightly builds. Rust has adopted a train-based release
|
||||||
model with regular releases every six weeks. Rust 1.1 beta was made available at
|
model with regular releases every six weeks. Rust 1.1 beta was made available at
|
||||||
the same time of the release of Rust 1.0.
|
the same time of the release of Rust 1.0.
|
||||||
|
|
||||||
Although Rust is a relatively low-level language, Rust has some functional
|
Although Rust is a relatively low-level language, Rust has some functional
|
||||||
|
@ -5,13 +5,13 @@ contributors:
|
|||||||
filename: learnself.self
|
filename: learnself.self
|
||||||
---
|
---
|
||||||
|
|
||||||
Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
|
Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
|
||||||
|
|
||||||
Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots.
|
Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots.
|
||||||
|
|
||||||
# Constructing objects
|
# Constructing objects
|
||||||
|
|
||||||
The inbuild Self parser can construct objects, including method objects.
|
The inbuild Self parser can construct objects, including method objects.
|
||||||
|
|
||||||
```
|
```
|
||||||
"This is a comment"
|
"This is a comment"
|
||||||
@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects.
|
|||||||
x <- 20.
|
x <- 20.
|
||||||
|)
|
|)
|
||||||
|
|
||||||
"An object which understands the method 'doubleX' which
|
"An object which understands the method 'doubleX' which
|
||||||
doubles the value of x and then returns the object"
|
doubles the value of x and then returns the object"
|
||||||
(|
|
(|
|
||||||
x <- 20.
|
x <- 20.
|
||||||
doubleX = (x: x * 2. self)
|
doubleX = (x: x * 2. self)
|
||||||
|)
|
|)
|
||||||
|
|
||||||
"An object which understands all the messages
|
"An object which understands all the messages
|
||||||
that 'traits point' understands". The parser
|
that 'traits point' understands". The parser
|
||||||
looks up 'traits point' by sending the messages
|
looks up 'traits point' by sending the messages
|
||||||
'traits' then 'point' to a known object called
|
'traits' then 'point' to a known object called
|
||||||
the 'lobby'. It looks up the 'true' object by
|
the 'lobby'. It looks up the 'true' object by
|
||||||
also sending the message 'true' to the lobby."
|
also sending the message 'true' to the lobby."
|
||||||
(| parent* = traits point.
|
(| parent* = traits point.
|
||||||
x = 7.
|
x = 7.
|
||||||
@ -63,19 +63,19 @@ also sending the message 'true' to the lobby."
|
|||||||
Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
|
Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
|
||||||
|
|
||||||
```
|
```
|
||||||
"unary message, sends 'printLine' to the object '23'
|
"unary message, sends 'printLine' to the object '23'
|
||||||
which prints the string '23' to stdout and returns the receiving object (ie 23)"
|
which prints the string '23' to stdout and returns the receiving object (ie 23)"
|
||||||
23 printLine
|
23 printLine
|
||||||
|
|
||||||
"sends the message '+' with '7' to '23', then the message '*' with '8' to the result"
|
"sends the message '+' with '7' to '23', then the message '*' with '8' to the result"
|
||||||
(23 + 7) * 8
|
(23 + 7) * 8
|
||||||
|
|
||||||
"sends 'power:' to '2' with '8' returns 256"
|
"sends 'power:' to '2' with '8' returns 256"
|
||||||
2 power: 8
|
2 power: 8
|
||||||
|
|
||||||
"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
|
"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
|
||||||
Returns 1, the index of 'e' in 'hello'."
|
Returns 1, the index of 'e' in 'hello'."
|
||||||
'hello' keyOf: 'e' IfAbsent: -1
|
'hello' keyOf: 'e' IfAbsent: -1
|
||||||
```
|
```
|
||||||
|
|
||||||
# Blocks
|
# Blocks
|
||||||
@ -90,13 +90,13 @@ Examples of the use of a block:
|
|||||||
|
|
||||||
```
|
```
|
||||||
"returns 'HELLO'"
|
"returns 'HELLO'"
|
||||||
'hello' copyMutable mapBy: [|:c| c capitalize]
|
'hello' copyMutable mapBy: [|:c| c capitalize]
|
||||||
|
|
||||||
"returns 'Nah'"
|
"returns 'Nah'"
|
||||||
'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
|
'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
|
||||||
|
|
||||||
"returns 'HaLLO'"
|
"returns 'HaLLO'"
|
||||||
'hello' copyMutable mapBy: [|:c|
|
'hello' copyMutable mapBy: [|:c|
|
||||||
c = 'e' ifTrue: [c capitalize]
|
c = 'e' ifTrue: [c capitalize]
|
||||||
False: ['a']]
|
False: ['a']]
|
||||||
```
|
```
|
||||||
@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately.
|
|||||||
|
|
||||||
```
|
```
|
||||||
"returns An 'E'! How icky!"
|
"returns An 'E'! How icky!"
|
||||||
'hello' copyMutable mapBy: [|:c. tmp <- ''|
|
'hello' copyMutable mapBy: [|:c. tmp <- ''|
|
||||||
tmp: c capitalize.
|
tmp: c capitalize.
|
||||||
tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
|
tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
|
||||||
c capitalize
|
c capitalize
|
||||||
@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t
|
|||||||
x: 15.
|
x: 15.
|
||||||
"Repeatedly sends 'value' to the first block while the result of sending 'value' to the
|
"Repeatedly sends 'value' to the first block while the result of sending 'value' to the
|
||||||
second block is the 'true' object"
|
second block is the 'true' object"
|
||||||
[x > 0] whileTrue: [x: x - 1].
|
[x > 0] whileTrue: [x: x - 1].
|
||||||
x
|
x
|
||||||
] value
|
] value
|
||||||
```
|
```
|
||||||
@ -130,12 +130,12 @@ Methods are like blocks but they are not within a context but instead are stored
|
|||||||
|
|
||||||
```
|
```
|
||||||
"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'.
|
"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'.
|
||||||
Sending the message 'reduceXTo: 10' to this object will put
|
Sending the message 'reduceXTo: 10' to this object will put
|
||||||
the object '10' in the 'x' slot and return the original object"
|
the object '10' in the 'x' slot and return the original object"
|
||||||
(|
|
(|
|
||||||
x <- 50.
|
x <- 50.
|
||||||
reduceXTo: y = (
|
reduceXTo: y = (
|
||||||
[x > y] whileTrue: [x: x - 1].
|
[x > y] whileTrue: [x: x - 1].
|
||||||
self)
|
self)
|
||||||
|)
|
|)
|
||||||
.
|
.
|
||||||
|
@ -11,28 +11,28 @@ contributors:
|
|||||||
Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`.
|
Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`.
|
||||||
|
|
||||||
|
|
||||||
##Allowable characters:
|
##Allowable characters:
|
||||||
- a-z
|
- a-z
|
||||||
- A-Z
|
- A-Z
|
||||||
- 0-9
|
- 0-9
|
||||||
- .+/\*~<>@%|&?
|
- .+/\*~<>@%|&?
|
||||||
- blank, tab, cr, ff, lf
|
- blank, tab, cr, ff, lf
|
||||||
|
|
||||||
##Variables:
|
##Variables:
|
||||||
- variables must be declared before use
|
- variables must be declared before use
|
||||||
- shared vars must begin with uppercase
|
- shared vars must begin with uppercase
|
||||||
- local vars must begin with lowercase
|
- local vars must begin with lowercase
|
||||||
- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
|
- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
|
||||||
|
|
||||||
##Variable scope:
|
##Variable scope:
|
||||||
- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
|
- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
|
||||||
- Method Temporary: local to a method
|
- Method Temporary: local to a method
|
||||||
- Block Temporary: local to a block
|
- Block Temporary: local to a block
|
||||||
- Pool: variables in a Dictionary object
|
- Pool: variables in a Dictionary object
|
||||||
- Method Parameters: automatic local vars created as a result of message call with params
|
- Method Parameters: automatic local vars created as a result of message call with params
|
||||||
- Block Parameters: automatic local vars created as a result of value: message call
|
- Block Parameters: automatic local vars created as a result of value: message call
|
||||||
- Class: shared with all instances of one class & its subclasses
|
- Class: shared with all instances of one class & its subclasses
|
||||||
- Class Instance: unique to each instance of a class
|
- Class Instance: unique to each instance of a class
|
||||||
- Instance Variables: unique to each instance
|
- Instance Variables: unique to each instance
|
||||||
|
|
||||||
`"Comments are enclosed in quotes"`
|
`"Comments are enclosed in quotes"`
|
||||||
@ -53,7 +53,7 @@ Transcript cr. "carriage return / l
|
|||||||
Transcript endEntry. "flush the output buffer"
|
Transcript endEntry. "flush the output buffer"
|
||||||
```
|
```
|
||||||
|
|
||||||
##Assignment:
|
##Assignment:
|
||||||
```
|
```
|
||||||
| x y |
|
| x y |
|
||||||
x _ 4. "assignment (Squeak) <-"
|
x _ 4. "assignment (Squeak) <-"
|
||||||
@ -72,7 +72,7 @@ y := x deepCopy. "copy object and ins
|
|||||||
y := x veryDeepCopy. "complete tree copy using a dictionary"
|
y := x veryDeepCopy. "complete tree copy using a dictionary"
|
||||||
```
|
```
|
||||||
|
|
||||||
##Constants:
|
##Constants:
|
||||||
```
|
```
|
||||||
| b |
|
| b |
|
||||||
b := true. "true constant"
|
b := true. "true constant"
|
||||||
@ -93,7 +93,7 @@ x := #('abc' 2 $a). "mixing of types all
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Booleans:
|
## Booleans:
|
||||||
```
|
```
|
||||||
| b x y |
|
| b x y |
|
||||||
x := 1. y := 2.
|
x := 1. y := 2.
|
||||||
@ -132,7 +132,7 @@ b := $A isLowercase. "test if lower case
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Arithmetic expressions:
|
## Arithmetic expressions:
|
||||||
```
|
```
|
||||||
| x |
|
| x |
|
||||||
x := 6 + 3. "addition"
|
x := 6 + 3. "addition"
|
||||||
@ -190,7 +190,7 @@ x := 100 atRandom. "quick random number
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
##Bitwise Manipulation:
|
##Bitwise Manipulation:
|
||||||
```
|
```
|
||||||
| b x |
|
| b x |
|
||||||
x := 16rFF bitAnd: 16r0F. "and bits"
|
x := 16rFF bitAnd: 16r0F. "and bits"
|
||||||
@ -207,7 +207,7 @@ b := 16rFF noMask: 16r0F. "test if all bits se
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Conversion:
|
## Conversion:
|
||||||
```
|
```
|
||||||
| x |
|
| x |
|
||||||
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
|
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
|
||||||
@ -223,15 +223,15 @@ x := 15 storeStringBase: 16.
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Blocks:
|
## Blocks:
|
||||||
- blocks are objects and may be assigned to a variable
|
- blocks are objects and may be assigned to a variable
|
||||||
- value is last expression evaluated unless explicit return
|
- value is last expression evaluated unless explicit return
|
||||||
- blocks may be nested
|
- blocks may be nested
|
||||||
- specification [ arguments | | localvars | expressions ]
|
- specification [ arguments | | localvars | expressions ]
|
||||||
- Squeak does not currently support localvars in blocks
|
- Squeak does not currently support localvars in blocks
|
||||||
- max of three arguments allowed
|
- max of three arguments allowed
|
||||||
- `^`expression terminates block & method (exits all nested blocks)
|
- `^`expression terminates block & method (exits all nested blocks)
|
||||||
- blocks intended for long term storage should not contain `^`
|
- blocks intended for long term storage should not contain `^`
|
||||||
|
|
||||||
```
|
```
|
||||||
| x y z |
|
| x y z |
|
||||||
@ -241,18 +241,18 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu
|
|||||||
"x := [ | z | z := 1.]. *** localvars not available in squeak blocks"
|
"x := [ | z | z := 1.]. *** localvars not available in squeak blocks"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Method calls:
|
## Method calls:
|
||||||
- unary methods are messages with no arguments
|
- unary methods are messages with no arguments
|
||||||
- binary methods
|
- binary methods
|
||||||
- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
|
- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
|
||||||
- accessing (get/set methods)
|
- accessing (get/set methods)
|
||||||
- testing (boolean tests - is)
|
- testing (boolean tests - is)
|
||||||
- comparing (boolean tests with parameter
|
- comparing (boolean tests with parameter
|
||||||
- displaying (gui related methods)
|
- displaying (gui related methods)
|
||||||
- printing (methods for printing)
|
- printing (methods for printing)
|
||||||
- updating (receive notification of changes)
|
- updating (receive notification of changes)
|
||||||
- private (methods private to class)
|
- private (methods private to class)
|
||||||
- instance-creation (class methods for creating instance)
|
- instance-creation (class methods for creating instance)
|
||||||
```
|
```
|
||||||
| x |
|
| x |
|
||||||
x := 2 sqrt. "unary message"
|
x := 2 sqrt. "unary message"
|
||||||
@ -299,7 +299,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr].
|
|||||||
result := (switch at: $B) value.
|
result := (switch at: $B) value.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Iteration statements:
|
## Iteration statements:
|
||||||
```
|
```
|
||||||
| x y |
|
| x y |
|
||||||
x := 4. y := 1.
|
x := 4. y := 1.
|
||||||
@ -311,7 +311,7 @@ x timesRepeat: [y := y * 2]. "times repear loop (
|
|||||||
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
|
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Character:
|
## Character:
|
||||||
```
|
```
|
||||||
| x y |
|
| x y |
|
||||||
x := $A. "character assignment"
|
x := $A. "character assignment"
|
||||||
@ -544,7 +544,7 @@ y := x asSet. "convert to set coll
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Set: like Bag except duplicates not allowed
|
## Set: like Bag except duplicates not allowed
|
||||||
## IdentitySet: uses identity test (== rather than =)
|
## IdentitySet: uses identity test (== rather than =)
|
||||||
```
|
```
|
||||||
| b x y sum max |
|
| b x y sum max |
|
||||||
x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
|
x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
|
||||||
@ -603,7 +603,7 @@ y := x asBag. "convert to bag coll
|
|||||||
y := x asSet. "convert to set collection"
|
y := x asSet. "convert to set collection"
|
||||||
```
|
```
|
||||||
|
|
||||||
##Associations:
|
##Associations:
|
||||||
```
|
```
|
||||||
| x y |
|
| x y |
|
||||||
x := #myVar->'hello'.
|
x := #myVar->'hello'.
|
||||||
|
@ -3,7 +3,7 @@ language: swift
|
|||||||
contributors:
|
contributors:
|
||||||
- ["Grant Timmerman", "http://github.com/grant"]
|
- ["Grant Timmerman", "http://github.com/grant"]
|
||||||
- ["Christopher Bess", "http://github.com/cbess"]
|
- ["Christopher Bess", "http://github.com/cbess"]
|
||||||
- ["Joey Huang", "http://github.com/kamidox"]
|
- ["Joey Huang", "http://github.com/kamidox"]
|
||||||
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||||
filename: learnswift.swift
|
filename: learnswift.swift
|
||||||
---
|
---
|
||||||
@ -74,7 +74,7 @@ if someOptionalString != nil {
|
|||||||
if someOptionalString!.hasPrefix("opt") {
|
if someOptionalString!.hasPrefix("opt") {
|
||||||
print("has the prefix")
|
print("has the prefix")
|
||||||
}
|
}
|
||||||
|
|
||||||
let empty = someOptionalString?.isEmpty
|
let empty = someOptionalString?.isEmpty
|
||||||
}
|
}
|
||||||
someOptionalString = nil
|
someOptionalString = nil
|
||||||
@ -99,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Comment here
|
Comment here
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Nested comments are also supported
|
Nested comments are also supported
|
||||||
*/
|
*/
|
||||||
@ -298,7 +298,7 @@ print(numbers) // [3, 6, 18]
|
|||||||
// Structures and classes have very similar capabilites
|
// Structures and classes have very similar capabilites
|
||||||
struct NamesTable {
|
struct NamesTable {
|
||||||
let names = [String]()
|
let names = [String]()
|
||||||
|
|
||||||
// Custom subscript
|
// Custom subscript
|
||||||
subscript(index: Int) -> String {
|
subscript(index: Int) -> String {
|
||||||
return names[index]
|
return names[index]
|
||||||
@ -329,7 +329,7 @@ public class Shape {
|
|||||||
|
|
||||||
internal class Rect: Shape {
|
internal class Rect: Shape {
|
||||||
var sideLength: Int = 1
|
var sideLength: Int = 1
|
||||||
|
|
||||||
// Custom getter and setter property
|
// Custom getter and setter property
|
||||||
private var perimeter: Int {
|
private var perimeter: Int {
|
||||||
get {
|
get {
|
||||||
@ -340,11 +340,11 @@ internal class Rect: Shape {
|
|||||||
sideLength = newValue / 4
|
sideLength = newValue / 4
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lazily load a property
|
// Lazily load a property
|
||||||
// subShape remains nil (uninitialized) until getter called
|
// subShape remains nil (uninitialized) until getter called
|
||||||
lazy var subShape = Rect(sideLength: 4)
|
lazy var subShape = Rect(sideLength: 4)
|
||||||
|
|
||||||
// If you don't need a custom getter and setter,
|
// If you don't need a custom getter and setter,
|
||||||
// but still want to run code before and after getting or setting
|
// but still want to run code before and after getting or setting
|
||||||
// a property, you can use `willSet` and `didSet`
|
// a property, you can use `willSet` and `didSet`
|
||||||
@ -354,19 +354,19 @@ internal class Rect: Shape {
|
|||||||
print(someIdentifier)
|
print(someIdentifier)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
init(sideLength: Int) {
|
init(sideLength: Int) {
|
||||||
self.sideLength = sideLength
|
self.sideLength = sideLength
|
||||||
// always super.init last when init custom properties
|
// always super.init last when init custom properties
|
||||||
super.init()
|
super.init()
|
||||||
}
|
}
|
||||||
|
|
||||||
func shrink() {
|
func shrink() {
|
||||||
if sideLength > 0 {
|
if sideLength > 0 {
|
||||||
--sideLength
|
--sideLength
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override func getArea() -> Int {
|
override func getArea() -> Int {
|
||||||
return sideLength * sideLength
|
return sideLength * sideLength
|
||||||
}
|
}
|
||||||
@ -398,13 +398,13 @@ class Circle: Shape {
|
|||||||
override func getArea() -> Int {
|
override func getArea() -> Int {
|
||||||
return 3 * radius * radius
|
return 3 * radius * radius
|
||||||
}
|
}
|
||||||
|
|
||||||
// Place a question mark postfix after `init` is an optional init
|
// Place a question mark postfix after `init` is an optional init
|
||||||
// which can return nil
|
// which can return nil
|
||||||
init?(radius: Int) {
|
init?(radius: Int) {
|
||||||
self.radius = radius
|
self.radius = radius
|
||||||
super.init()
|
super.init()
|
||||||
|
|
||||||
if radius <= 0 {
|
if radius <= 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -458,7 +458,7 @@ enum Furniture {
|
|||||||
case Desk(height: Int)
|
case Desk(height: Int)
|
||||||
// Associate with String and Int
|
// Associate with String and Int
|
||||||
case Chair(String, Int)
|
case Chair(String, Int)
|
||||||
|
|
||||||
func description() -> String {
|
func description() -> String {
|
||||||
switch self {
|
switch self {
|
||||||
case .Desk(let height):
|
case .Desk(let height):
|
||||||
@ -497,7 +497,7 @@ protocol ShapeGenerator {
|
|||||||
|
|
||||||
class MyShape: Rect {
|
class MyShape: Rect {
|
||||||
var delegate: TransformShape?
|
var delegate: TransformShape?
|
||||||
|
|
||||||
func grow() {
|
func grow() {
|
||||||
sideLength += 2
|
sideLength += 2
|
||||||
|
|
||||||
@ -532,7 +532,7 @@ extension Int {
|
|||||||
var customProperty: String {
|
var customProperty: String {
|
||||||
return "This is \(self)"
|
return "This is \(self)"
|
||||||
}
|
}
|
||||||
|
|
||||||
func multiplyBy(num: Int) -> Int {
|
func multiplyBy(num: Int) -> Int {
|
||||||
return num * self
|
return num * self
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ programming language. It can also be used as a portable C library, even in
|
|||||||
cases where no scripting capability is needed, as it provides data structures
|
cases where no scripting capability is needed, as it provides data structures
|
||||||
such as dynamic strings, lists, and hash tables. The C library also provides
|
such as dynamic strings, lists, and hash tables. The C library also provides
|
||||||
portable functionality for loading dynamic libraries, string formatting and
|
portable functionality for loading dynamic libraries, string formatting and
|
||||||
code conversion, filesystem operations, network operations, and more.
|
code conversion, filesystem operations, network operations, and more.
|
||||||
Various features of Tcl stand out:
|
Various features of Tcl stand out:
|
||||||
|
|
||||||
* Convenient cross-platform networking API
|
* Convenient cross-platform networking API
|
||||||
@ -58,14 +58,14 @@ lighter that that of Lisp, just gets out of the way.
|
|||||||
#! /bin/env tclsh
|
#! /bin/env tclsh
|
||||||
|
|
||||||
################################################################################
|
################################################################################
|
||||||
## 1. Guidelines
|
## 1. Guidelines
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
# Tcl is not Bash or C! This needs to be said because standard shell quoting
|
# Tcl is not Bash or C! This needs to be said because standard shell quoting
|
||||||
# habits almost work in Tcl and it is common for people to pick up Tcl and try
|
# habits almost work in Tcl and it is common for people to pick up Tcl and try
|
||||||
# to get by with syntax they know from another language. It works at first,
|
# to get by with syntax they know from another language. It works at first,
|
||||||
# but soon leads to frustration with more complex scripts.
|
# but soon leads to frustration with more complex scripts.
|
||||||
|
|
||||||
# Braces are just a quoting mechanism, not a code block constructor or a list
|
# Braces are just a quoting mechanism, not a code block constructor or a list
|
||||||
# constructor. Tcl doesn't have either of those things. Braces are used,
|
# constructor. Tcl doesn't have either of those things. Braces are used,
|
||||||
# though, to escape special characters in procedure bodies and in strings that
|
# though, to escape special characters in procedure bodies and in strings that
|
||||||
@ -73,7 +73,7 @@ lighter that that of Lisp, just gets out of the way.
|
|||||||
|
|
||||||
|
|
||||||
################################################################################
|
################################################################################
|
||||||
## 2. Syntax
|
## 2. Syntax
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
# Every line is a command. The first word is the name of the command, and
|
# Every line is a command. The first word is the name of the command, and
|
||||||
@ -83,13 +83,13 @@ lighter that that of Lisp, just gets out of the way.
|
|||||||
# are used, they are not a string constructor, but just another escaping
|
# are used, they are not a string constructor, but just another escaping
|
||||||
# character.
|
# character.
|
||||||
|
|
||||||
set greeting1 Sal
|
set greeting1 Sal
|
||||||
set greeting2 ut
|
set greeting2 ut
|
||||||
set greeting3 ations
|
set greeting3 ations
|
||||||
|
|
||||||
|
|
||||||
#semicolon also delimits commands
|
#semicolon also delimits commands
|
||||||
set greeting1 Sal; set greeting2 ut; set greeting3 ations
|
set greeting1 Sal; set greeting2 ut; set greeting3 ations
|
||||||
|
|
||||||
|
|
||||||
# Dollar sign introduces variable substitution
|
# Dollar sign introduces variable substitution
|
||||||
@ -126,11 +126,11 @@ puts lots\nof\n\n\n\n\n\nnewlines
|
|||||||
set somevar {
|
set somevar {
|
||||||
This is a literal $ sign, and this \} escaped
|
This is a literal $ sign, and this \} escaped
|
||||||
brace remains uninterpreted
|
brace remains uninterpreted
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# In a word enclosed in double quotes, whitespace characters lose their special
|
# In a word enclosed in double quotes, whitespace characters lose their special
|
||||||
# meaning
|
# meaning
|
||||||
set name Neo
|
set name Neo
|
||||||
set greeting "Hello, $name"
|
set greeting "Hello, $name"
|
||||||
|
|
||||||
@ -178,7 +178,7 @@ set greeting "Hello $people::person1::name"
|
|||||||
|
|
||||||
|
|
||||||
################################################################################
|
################################################################################
|
||||||
## 3. A Few Notes
|
## 3. A Few Notes
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
# All other functionality is implemented via commands. From this point on,
|
# All other functionality is implemented via commands. From this point on,
|
||||||
@ -193,8 +193,8 @@ set greeting "Hello $people::person1::name"
|
|||||||
namespace delete ::
|
namespace delete ::
|
||||||
|
|
||||||
|
|
||||||
# Because of name resolution behaviour, it's safer to use the "variable" command to
|
# Because of name resolution behaviour, it's safer to use the "variable" command to
|
||||||
# declare or to assign a value to a namespace. If a variable called "name" already
|
# declare or to assign a value to a namespace. If a variable called "name" already
|
||||||
# exists in the global namespace, using "set" here will assign a value to the global variable
|
# exists in the global namespace, using "set" here will assign a value to the global variable
|
||||||
# instead of creating a new variable in the local namespace.
|
# instead of creating a new variable in the local namespace.
|
||||||
namespace eval people {
|
namespace eval people {
|
||||||
@ -210,7 +210,7 @@ set people::person1::name Neo
|
|||||||
|
|
||||||
|
|
||||||
################################################################################
|
################################################################################
|
||||||
## 4. Commands
|
## 4. Commands
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|
||||||
# Math can be done with the "expr" command.
|
# Math can be done with the "expr" command.
|
||||||
@ -295,7 +295,7 @@ while {$i < 10} {
|
|||||||
|
|
||||||
|
|
||||||
# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values
|
# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values
|
||||||
set amounts 10\ 33\ 18
|
set amounts 10\ 33\ 18
|
||||||
set amount [lindex $amounts 1]
|
set amount [lindex $amounts 1]
|
||||||
|
|
||||||
|
|
||||||
@ -339,7 +339,7 @@ eval {set name Neo}
|
|||||||
eval [list set greeting "Hello, $name"]
|
eval [list set greeting "Hello, $name"]
|
||||||
|
|
||||||
|
|
||||||
# Therefore, when using "eval", use [list] to build up a desired command
|
# Therefore, when using "eval", use [list] to build up a desired command
|
||||||
set command {set name}
|
set command {set name}
|
||||||
lappend command {Archibald Sorbisol}
|
lappend command {Archibald Sorbisol}
|
||||||
eval $command
|
eval $command
|
||||||
@ -355,7 +355,7 @@ eval $command ;# There is an error here, because there are too many arguments \
|
|||||||
# This mistake can easily occur with the "subst" command.
|
# This mistake can easily occur with the "subst" command.
|
||||||
set replacement {Archibald Sorbisol}
|
set replacement {Archibald Sorbisol}
|
||||||
set command {set name $replacement}
|
set command {set name $replacement}
|
||||||
set command [subst $command]
|
set command [subst $command]
|
||||||
eval $command ;# The same error as before: too many arguments to "set" in \
|
eval $command ;# The same error as before: too many arguments to "set" in \
|
||||||
{set name Archibald Sorbisol}
|
{set name Archibald Sorbisol}
|
||||||
|
|
||||||
@ -364,12 +364,12 @@ eval $command ;# The same error as before: too many arguments to "set" in \
|
|||||||
# command.
|
# command.
|
||||||
set replacement [list {Archibald Sorbisol}]
|
set replacement [list {Archibald Sorbisol}]
|
||||||
set command {set name $replacement}
|
set command {set name $replacement}
|
||||||
set command [subst $command]
|
set command [subst $command]
|
||||||
eval $command
|
eval $command
|
||||||
|
|
||||||
|
|
||||||
# It is extremely common to see the "list" command being used to properly
|
# It is extremely common to see the "list" command being used to properly
|
||||||
# format values that are substituted into Tcl script templates. There are
|
# format values that are substituted into Tcl script templates. There are
|
||||||
# several examples of this, below.
|
# several examples of this, below.
|
||||||
|
|
||||||
|
|
||||||
@ -422,12 +422,12 @@ proc while {condition script} {
|
|||||||
|
|
||||||
# The "coroutine" command creates a separate call stack, along with a command
|
# The "coroutine" command creates a separate call stack, along with a command
|
||||||
# to enter that call stack. The "yield" command suspends execution in that
|
# to enter that call stack. The "yield" command suspends execution in that
|
||||||
# stack.
|
# stack.
|
||||||
proc countdown {} {
|
proc countdown {} {
|
||||||
#send something back to the initial "coroutine" command
|
#send something back to the initial "coroutine" command
|
||||||
yield
|
yield
|
||||||
|
|
||||||
set count 3
|
set count 3
|
||||||
while {$count > 1} {
|
while {$count > 1} {
|
||||||
yield [incr count -1]
|
yield [incr count -1]
|
||||||
}
|
}
|
||||||
@ -435,12 +435,12 @@ proc countdown {} {
|
|||||||
}
|
}
|
||||||
coroutine countdown1 countdown
|
coroutine countdown1 countdown
|
||||||
coroutine countdown2 countdown
|
coroutine countdown2 countdown
|
||||||
puts [countdown 1] ;# -> 2
|
puts [countdown 1] ;# -> 2
|
||||||
puts [countdown 2] ;# -> 2
|
puts [countdown 2] ;# -> 2
|
||||||
puts [countdown 1] ;# -> 1
|
puts [countdown 1] ;# -> 1
|
||||||
puts [countdown 1] ;# -> 0
|
puts [countdown 1] ;# -> 0
|
||||||
puts [coundown 1] ;# -> invalid command name "countdown1"
|
puts [coundown 1] ;# -> invalid command name "countdown1"
|
||||||
puts [countdown 2] ;# -> 1
|
puts [countdown 2] ;# -> 1
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
@ -17,7 +17,7 @@ Module Module1
|
|||||||
' This navigation system is explained however as we go deeper into this
|
' This navigation system is explained however as we go deeper into this
|
||||||
' tutorial, you'll understand what it all means.
|
' tutorial, you'll understand what it all means.
|
||||||
Console.Title = ("Learn X in Y Minutes")
|
Console.Title = ("Learn X in Y Minutes")
|
||||||
Console.WriteLine("NAVIGATION") 'Display
|
Console.WriteLine("NAVIGATION") 'Display
|
||||||
Console.WriteLine("")
|
Console.WriteLine("")
|
||||||
Console.ForegroundColor = ConsoleColor.Green
|
Console.ForegroundColor = ConsoleColor.Green
|
||||||
Console.WriteLine("1. Hello World Output")
|
Console.WriteLine("1. Hello World Output")
|
||||||
@ -39,13 +39,13 @@ Module Module1
|
|||||||
Case "2" 'Hello Input
|
Case "2" 'Hello Input
|
||||||
Console.Clear()
|
Console.Clear()
|
||||||
HelloWorldInput()
|
HelloWorldInput()
|
||||||
Case "3" 'Calculating Whole Numbers
|
Case "3" 'Calculating Whole Numbers
|
||||||
Console.Clear()
|
Console.Clear()
|
||||||
CalculatingWholeNumbers()
|
CalculatingWholeNumbers()
|
||||||
Case "4" 'Calculting Decimal Numbers
|
Case "4" 'Calculting Decimal Numbers
|
||||||
Console.Clear()
|
Console.Clear()
|
||||||
CalculatingDecimalNumbers()
|
CalculatingDecimalNumbers()
|
||||||
Case "5" 'Working Calcculator
|
Case "5" 'Working Calcculator
|
||||||
Console.Clear()
|
Console.Clear()
|
||||||
WorkingCalculator()
|
WorkingCalculator()
|
||||||
Case "6" 'Using Do While Loops
|
Case "6" 'Using Do While Loops
|
||||||
@ -74,7 +74,7 @@ Module Module1
|
|||||||
'One - I'm using numbers to help with the above navigation when I come back
|
'One - I'm using numbers to help with the above navigation when I come back
|
||||||
'later to build it.
|
'later to build it.
|
||||||
|
|
||||||
'We use private subs to seperate different sections of the program.
|
'We use private subs to seperate different sections of the program.
|
||||||
Private Sub HelloWorldOutput()
|
Private Sub HelloWorldOutput()
|
||||||
'Title of Console Application
|
'Title of Console Application
|
||||||
Console.Title = "Hello World Ouput | Learn X in Y Minutes"
|
Console.Title = "Hello World Ouput | Learn X in Y Minutes"
|
||||||
@ -172,7 +172,7 @@ Module Module1
|
|||||||
'program more than once.
|
'program more than once.
|
||||||
Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes"
|
Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes"
|
||||||
Dim answer As String 'We use the variable "String" as the answer is text
|
Dim answer As String 'We use the variable "String" as the answer is text
|
||||||
Do 'We start the program with
|
Do 'We start the program with
|
||||||
Console.Write("First number: ")
|
Console.Write("First number: ")
|
||||||
Dim a As Double = Console.ReadLine
|
Dim a As Double = Console.ReadLine
|
||||||
Console.Write("Second number: ")
|
Console.Write("Second number: ")
|
||||||
@ -192,7 +192,7 @@ Module Module1
|
|||||||
Console.WriteLine(" = " + f.ToString.PadLeft(3))
|
Console.WriteLine(" = " + f.ToString.PadLeft(3))
|
||||||
Console.ReadLine()
|
Console.ReadLine()
|
||||||
'Ask the question, does the user wish to continue? Unfortunately it
|
'Ask the question, does the user wish to continue? Unfortunately it
|
||||||
'is case sensitive.
|
'is case sensitive.
|
||||||
Console.Write("Would you like to continue? (yes / no)")
|
Console.Write("Would you like to continue? (yes / no)")
|
||||||
'The program grabs the variable and prints and starts again.
|
'The program grabs the variable and prints and starts again.
|
||||||
answer = Console.ReadLine
|
answer = Console.ReadLine
|
||||||
@ -208,8 +208,8 @@ Module Module1
|
|||||||
|
|
||||||
Console.Title = "Using For Loops | Learn X in Y Minutes"
|
Console.Title = "Using For Loops | Learn X in Y Minutes"
|
||||||
'Declare Variable and what number it should count down in Step -1,
|
'Declare Variable and what number it should count down in Step -1,
|
||||||
'Step -2, Step -3 ect.
|
'Step -2, Step -3 ect.
|
||||||
For i As Integer = 10 To 0 Step -1
|
For i As Integer = 10 To 0 Step -1
|
||||||
Console.WriteLine(i.ToString) 'Print the value of the counter
|
Console.WriteLine(i.ToString) 'Print the value of the counter
|
||||||
Next i 'Calculate new value
|
Next i 'Calculate new value
|
||||||
Console.WriteLine("Start") 'Lets start the program baby!!
|
Console.WriteLine("Start") 'Lets start the program baby!!
|
||||||
@ -274,8 +274,8 @@ End Module
|
|||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
|
I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
|
||||||
|
|
||||||
I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more.
|
I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more.
|
||||||
|
|
||||||
The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
|
The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
|
||||||
|
@ -38,10 +38,10 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
|
|||||||
|
|
||||||
<!-- Above is a typical XML file.
|
<!-- Above is a typical XML file.
|
||||||
It starts with a declaration, informing some metadata (optional).
|
It starts with a declaration, informing some metadata (optional).
|
||||||
|
|
||||||
XML uses a tree structure. Above, the root node is 'bookstore', which has
|
XML uses a tree structure. Above, the root node is 'bookstore', which has
|
||||||
three child nodes, all 'books'. Those nodes has more child nodes, and so on...
|
three child nodes, all 'books'. Those nodes has more child nodes, and so on...
|
||||||
|
|
||||||
Nodes are created using open/close tags, and childs are just nodes between
|
Nodes are created using open/close tags, and childs are just nodes between
|
||||||
the open and close tags.-->
|
the open and close tags.-->
|
||||||
|
|
||||||
@ -54,8 +54,8 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
|
|||||||
2 - Elements -> That's pure data.
|
2 - Elements -> That's pure data.
|
||||||
That's what the parser will retrieve from the XML file.
|
That's what the parser will retrieve from the XML file.
|
||||||
Elements appear between the open and close tags. -->
|
Elements appear between the open and close tags. -->
|
||||||
|
|
||||||
|
|
||||||
<!-- Below, an element with two attributes -->
|
<!-- Below, an element with two attributes -->
|
||||||
<file type="gif" id="4293">computer.gif</file>
|
<file type="gif" id="4293">computer.gif</file>
|
||||||
|
|
||||||
@ -68,14 +68,14 @@ A XML document is well-formated if it is syntactically correct.
|
|||||||
However, it is possible to inject more constraints in the document,
|
However, it is possible to inject more constraints in the document,
|
||||||
using document definitions, such as DTD and XML Schema.
|
using document definitions, such as DTD and XML Schema.
|
||||||
|
|
||||||
A XML document which follows a document definition is called valid,
|
A XML document which follows a document definition is called valid,
|
||||||
regarding that document.
|
regarding that document.
|
||||||
|
|
||||||
With this tool, you can check the XML data outside the application logic.
|
With this tool, you can check the XML data outside the application logic.
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
|
|
||||||
<!-- Below, you can see an simplified version of bookstore document,
|
<!-- Below, you can see an simplified version of bookstore document,
|
||||||
with the addition of DTD definition.-->
|
with the addition of DTD definition.-->
|
||||||
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
Loading…
Reference in New Issue
Block a user