mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 07:12:31 +03:00
Merge remote-tracking branch 'adambard/master'
Conflicts: java.html.markdown
This commit is contained in:
commit
bc21259249
@ -8,10 +8,10 @@ filename: learnamd.js
|
||||
|
||||
## Getting Started with AMD
|
||||
|
||||
The **Asynchronous Module Definition** API specifies a mechanism for defining
|
||||
JavaScript modules such that the module and its dependencies can be asynchronously
|
||||
loaded. This is particularly well suited for the browser environment where
|
||||
synchronous loading of modules incurs performance, usability, debugging, and
|
||||
The **Asynchronous Module Definition** API specifies a mechanism for defining
|
||||
JavaScript modules such that the module and its dependencies can be asynchronously
|
||||
loaded. This is particularly well suited for the browser environment where
|
||||
synchronous loading of modules incurs performance, usability, debugging, and
|
||||
cross-domain access problems.
|
||||
|
||||
### 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),
|
||||
`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
|
||||
```
|
||||
|
||||
Is `f(n)` O(g(n))?
|
||||
Is `3 log n + 100` O(log n)?
|
||||
Is `f(n)` O(g(n))?
|
||||
Is `3 log n + 100` O(log n)?
|
||||
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)).
|
||||
|
||||
*Example 2*
|
||||
*Example 2*
|
||||
|
||||
```
|
||||
f(n) = 3*n^2
|
||||
f(n) = 3*n^2
|
||||
g(n) = n
|
||||
```
|
||||
|
||||
Is `f(n)` O(g(n))?
|
||||
Is `3 * n^2` O(n)?
|
||||
Is `f(n)` O(g(n))?
|
||||
Is `3 * n^2` O(n)?
|
||||
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)).
|
||||
|
||||
### Big-Omega
|
||||
|
@ -252,7 +252,7 @@ grep "^foo.*bar$" file.txt
|
||||
grep -c "^foo.*bar$" file.txt
|
||||
# if you literally want to search for the string,
|
||||
# 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:
|
||||
|
@ -307,7 +307,7 @@ var stringSet: domain(string); // empty set of strings
|
||||
stringSet += "a";
|
||||
stringSet += "b";
|
||||
stringSet += "c";
|
||||
stringSet += "a"; // Redundant add "a"
|
||||
stringSet += "a"; // Redundant add "a"
|
||||
stringSet -= "c"; // Remove "c"
|
||||
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.
|
||||
proc whereProc( param N : int ): void
|
||||
where ( N > 0 ) {
|
||||
writeln( "N is greater than 0" );
|
||||
writeln( "N is greater than 0" );
|
||||
}
|
||||
|
||||
proc whereProc( param N : int ): void
|
||||
where ( N < 0 ) {
|
||||
writeln( "N is less than 0" );
|
||||
writeln( "N is less than 0" );
|
||||
}
|
||||
|
||||
whereProc( 10 );
|
||||
|
@ -142,11 +142,11 @@ You'll want to be familiar with Clojure. Make sure you understand everything in
|
||||
|
||||
### 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/)
|
||||
|
||||
Official docs
|
||||
Official docs
|
||||
[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)
|
||||
|
@ -6,7 +6,7 @@ contributors:
|
||||
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.
|
||||
|
||||
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!"); }
|
||||
|
||||
# Array comprehensions:
|
||||
cubes = (math.cube num for num in list)
|
||||
cubes = (math.cube num for num in list)
|
||||
#=>cubes = (function() {
|
||||
# var _i, _len, _results;
|
||||
# _results = [];
|
||||
|
@ -261,7 +261,7 @@ nil ; for false - and the empty list
|
||||
|
||||
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
|
||||
:adjustable t :fill-pointer t))
|
||||
|
||||
|
||||
*adjvec* ; => #(1 2 3)
|
||||
|
||||
;; Adding new element:
|
||||
|
@ -25,7 +25,7 @@ Multi-line comments look like this
|
||||
//public void MethodOrClassOrOtherWithParsableHelp() {}
|
||||
|
||||
// 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.Collections.Generic;
|
||||
using System.Dynamic;
|
||||
@ -48,7 +48,7 @@ namespace Learning.CSharp
|
||||
public class LearnCSharp
|
||||
{
|
||||
// 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
|
||||
Console.WriteLine("Hello World");
|
||||
@ -371,11 +371,11 @@ on a new line! ""Wow!"", the masses cried";
|
||||
//
|
||||
// INTERESTING FEATURES
|
||||
//
|
||||
|
||||
|
||||
// DEFAULT METHOD SIGNATURES
|
||||
|
||||
public // Visibility
|
||||
static // Allows for direct call on class without object
|
||||
static // Allows for direct call on class without object
|
||||
int // Return Type,
|
||||
MethodSignatures(
|
||||
int maxCount, // First variable, expects an int
|
||||
@ -383,7 +383,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
int another = 3,
|
||||
params string[] otherParams // captures all other parameters passed to method
|
||||
)
|
||||
{
|
||||
{
|
||||
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.
|
||||
// This method emulates the SetDefault of Python
|
||||
public static TValue SetDefault<TKey, TValue>(
|
||||
IDictionary<TKey, TValue> dictionary,
|
||||
TKey key,
|
||||
IDictionary<TKey, TValue> dictionary,
|
||||
TKey key,
|
||||
TValue defaultItem)
|
||||
{
|
||||
TValue result;
|
||||
@ -410,7 +410,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
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>
|
||||
{
|
||||
// We can iterate, since T is a IEnumerable
|
||||
@ -450,13 +450,13 @@ on a new line! ""Wow!"", the masses cried";
|
||||
|
||||
// GENERICS
|
||||
//
|
||||
var phonebook = new Dictionary<string, string>() {
|
||||
var phonebook = new Dictionary<string, string>() {
|
||||
{"Sarah", "212 555 5555"} // Add some entries to the phone book
|
||||
};
|
||||
|
||||
// Calling SETDEFAULT defined as a generic above
|
||||
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
|
||||
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.
|
||||
// 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.
|
||||
using (StreamWriter writer = new StreamWriter("log.txt"))
|
||||
{
|
||||
writer.WriteLine("Nothing suspicious here");
|
||||
// At the end of scope, resources will be released.
|
||||
// Even if an exception is thrown.
|
||||
}
|
||||
}
|
||||
|
||||
// PARALLEL FRAMEWORK
|
||||
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
|
||||
var websites = new string[] {
|
||||
"http://www.google.com", "http://www.reddit.com",
|
||||
var websites = new string[] {
|
||||
"http://www.google.com", "http://www.reddit.com",
|
||||
"http://www.shaunmccarthy.com"
|
||||
};
|
||||
var responses = new Dictionary<string, string>();
|
||||
|
||||
|
||||
// Will spin up separate threads for each request, and join on them
|
||||
// before going to the next step!
|
||||
Parallel.ForEach(websites,
|
||||
Parallel.ForEach(websites,
|
||||
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
|
||||
website =>
|
||||
{
|
||||
@ -534,7 +534,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
|
||||
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
|
||||
var bikes = new List<Bicycle>();
|
||||
bikes.Sort(); // Sorts the array
|
||||
@ -556,8 +556,8 @@ on a new line! ""Wow!"", the masses cried";
|
||||
// ASPARALLEL
|
||||
// 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);
|
||||
// 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
|
||||
// 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
|
||||
// cores
|
||||
|
||||
// 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
|
||||
|
||||
// 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);
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@ -629,7 +629,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
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
|
||||
public string Name { get; set; }
|
||||
|
||||
@ -676,7 +676,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
|
||||
// Constructors are a way of creating classes
|
||||
// This is a default constructor
|
||||
public Bicycle()
|
||||
public Bicycle()
|
||||
{
|
||||
this.Gear = 1; // you can access members of the object with the keyword this
|
||||
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)
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear,
|
||||
string name, bool hasCardsInSpokes, BikeBrand brand)
|
||||
string name, bool hasCardsInSpokes, BikeBrand brand)
|
||||
: base() // calls base first
|
||||
{
|
||||
Gear = startGear;
|
||||
Gear = startGear;
|
||||
Cadence = startCadence;
|
||||
_speed = startSpeed;
|
||||
Name = name;
|
||||
Name = name;
|
||||
_hasCardsInSpokes = hasCardsInSpokes;
|
||||
Brand = brand;
|
||||
}
|
||||
@ -857,7 +857,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
}
|
||||
|
||||
/// <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)
|
||||
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
|
||||
/// </summary>
|
||||
@ -882,7 +882,7 @@ on a new line! ""Wow!"", the masses cried";
|
||||
* ASP.NET Web Forms (old)
|
||||
* WebMatrix (tool)
|
||||
* Desktop Development
|
||||
* Windows Presentation Foundation (WPF) (new)
|
||||
* Windows Presentation Foundation (WPF) (new)
|
||||
* Winforms (old)
|
||||
|
||||
## Further Reading
|
||||
|
@ -8,19 +8,19 @@ contributors:
|
||||
filename: learncss.css
|
||||
---
|
||||
|
||||
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.
|
||||
CSS is the standard language that exists to keep the separation between
|
||||
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.
|
||||
CSS is the standard language that exists to keep the separation between
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
**NOTE:** Because the outcome of CSS consists of visual effects, in order to
|
||||
learn it, you need try everything in a
|
||||
**NOTE:** Because the outcome of CSS consists of visual effects, in order to
|
||||
learn it, you need try everything in a
|
||||
CSS playground like [dabblet](http://dabblet.com/).
|
||||
The main focus of this article is on the syntax and some general tips.
|
||||
|
||||
@ -78,8 +78,8 @@ div { }
|
||||
[otherAttr|='en'] { font-size:smaller; }
|
||||
|
||||
|
||||
/* and more importantly you can combine these together -- there shouldn't be
|
||||
any space between different parts because that makes it to have another
|
||||
/* and more importantly you can combine these together -- there shouldn't be
|
||||
any space between different parts because that makes it to have another
|
||||
meaning. */
|
||||
div.some-class[attr$='ue'] { }
|
||||
|
||||
@ -89,22 +89,22 @@ div.some-class[attr$='ue'] { }
|
||||
div.some-parent > .class-name {}
|
||||
|
||||
/* 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 */
|
||||
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? */
|
||||
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 */
|
||||
.i-am-before + .this-element { }
|
||||
|
||||
/* or any sibling before this */
|
||||
.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) */
|
||||
|
||||
/* for example for when an element is hovered */
|
||||
@ -125,7 +125,7 @@ selected:focus {}
|
||||
#################### */
|
||||
|
||||
selector {
|
||||
|
||||
|
||||
/* Units */
|
||||
width: 50%; /* in percent */
|
||||
font-size: 2em; /* times current font-size */
|
||||
@ -138,7 +138,7 @@ selector {
|
||||
width: 0.4vw; /* times horizontal width 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) */
|
||||
|
||||
|
||||
/* Colors */
|
||||
background-color: #F6E; /* in short hex */
|
||||
background-color: #F262E2; /* in long hex format */
|
||||
@ -150,10 +150,10 @@ selector {
|
||||
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) */
|
||||
|
||||
|
||||
|
||||
/* Images */
|
||||
background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
|
||||
|
||||
|
||||
/* Fonts */
|
||||
font-family: Arial;
|
||||
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>: -->
|
||||
<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. -->
|
||||
<style>
|
||||
a { color: purple; }
|
||||
</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. -->
|
||||
<div style="border: 1px solid red;">
|
||||
</div>
|
||||
@ -186,8 +186,8 @@ This has to be avoided as much as you can. -->
|
||||
|
||||
## Precedence
|
||||
|
||||
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.
|
||||
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.
|
||||
In these cases, one of the rules takes precedence over others.
|
||||
|
||||
Given the following CSS:
|
||||
@ -217,24 +217,24 @@ and the following markup:
|
||||
</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.
|
||||
|
||||
* `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.
|
||||
* `F` is next, because it is inline style.
|
||||
* `A` is next, because it is more "specific" than anything else.
|
||||
more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
|
||||
* `A` is next, because it is more "specific" than anything else.
|
||||
more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
|
||||
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.
|
||||
* Then is `B`
|
||||
* and lastly is `D`.
|
||||
|
||||
## Compatibility
|
||||
|
||||
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
|
||||
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
|
||||
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.
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: D
|
||||
filename: learnd.d
|
||||
language: D
|
||||
filename: learnd.d
|
||||
contributors:
|
||||
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
|
||||
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,
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
|
||||
// Numeric literals can use _ as a digit seperator for clarity
|
||||
while(n < 10_000) {
|
||||
n += n;
|
||||
@ -49,7 +49,7 @@ void main() {
|
||||
|
||||
// For and while are nice, but in D-land we prefer foreach
|
||||
// The .. creates a continuous range, excluding the end
|
||||
foreach(i; 1..1_000_000) {
|
||||
foreach(i; 1..1_000_000) {
|
||||
if(n % 2 == 0)
|
||||
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
|
||||
struct LinkedList(T) {
|
||||
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) {
|
||||
T data = null;
|
||||
|
||||
|
||||
// If there is only one template parameter, we can omit parens
|
||||
BinTree!T left;
|
||||
BinTree!T right;
|
||||
@ -101,7 +101,7 @@ alias NumTree = BinTree!double;
|
||||
// We can create function templates as well!
|
||||
|
||||
T max(T)(T a, T b) {
|
||||
if(a < b)
|
||||
if(a < b)
|
||||
return b;
|
||||
|
||||
return a;
|
||||
@ -114,7 +114,7 @@ void swap(T)(ref T a, ref T b) {
|
||||
auto temp = a;
|
||||
|
||||
a = b;
|
||||
b = temp;
|
||||
b = temp;
|
||||
}
|
||||
|
||||
// With templates, we can also parameterize on values, not just types
|
||||
@ -145,13 +145,13 @@ class MyClass(T, U) {
|
||||
class MyClass(T, U) {
|
||||
T _data;
|
||||
U _other;
|
||||
|
||||
|
||||
// Constructors are always named `this`
|
||||
this(T t, U u) {
|
||||
data = t;
|
||||
other = u;
|
||||
}
|
||||
|
||||
|
||||
// getters
|
||||
@property T data() {
|
||||
return _data;
|
||||
@ -161,7 +161,7 @@ class MyClass(T, U) {
|
||||
return _other;
|
||||
}
|
||||
|
||||
// setters
|
||||
// setters
|
||||
@property void data(T t) {
|
||||
_data = t;
|
||||
}
|
||||
@ -177,7 +177,7 @@ void main() {
|
||||
|
||||
mc.data = 7;
|
||||
mc.other = "seven";
|
||||
|
||||
|
||||
writeln(mc.data);
|
||||
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.
|
||||
|
||||
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
|
||||
functional algorithms (map, filter, reduce and friends) can be
|
||||
found in the wonderful `std.algorithm` module!
|
||||
@ -205,7 +205,7 @@ import std.range : iota; // builds an end-exclusive range
|
||||
void main() {
|
||||
// We want to print the sum of a list of squares of even ints
|
||||
// from 1 to 100. Easy!
|
||||
|
||||
|
||||
// Just pass lambda expressions as template parameters!
|
||||
// You can pass any old function you like, but lambdas are convenient here.
|
||||
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.
|
||||
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
|
||||
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
||||
In short, you can call functions whose first parameter
|
||||
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
||||
In short, you can call functions whose first parameter
|
||||
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!
|
||||
|
@ -81,7 +81,7 @@ example5() {
|
||||
// Where classBody can include instance methods and variables, but also
|
||||
// class methods and variables.
|
||||
class Example6Class {
|
||||
var example6InstanceVariable = "Example6 instance variable";
|
||||
var example6InstanceVariable = "Example6 instance variable";
|
||||
sayIt() {
|
||||
print(example6InstanceVariable);
|
||||
}
|
||||
@ -92,7 +92,7 @@ example6() {
|
||||
|
||||
// Class methods and variables are declared with "static" terms.
|
||||
class Example7Class {
|
||||
static var example7ClassVariable = "Example7 class variable";
|
||||
static var example7ClassVariable = "Example7 class variable";
|
||||
static sayItFromClass() {
|
||||
print(example7ClassVariable);
|
||||
}
|
||||
@ -111,7 +111,7 @@ example7() {
|
||||
// by default. But arrays and maps are not. They can be made constant by
|
||||
// declaring them "const".
|
||||
var example8A = const ["Example8 const array"],
|
||||
example8M = const {"someKey": "Example8 const map"};
|
||||
example8M = const {"someKey": "Example8 const map"};
|
||||
example8() {
|
||||
print(example8A[0]);
|
||||
print(example8M["someKey"]);
|
||||
@ -245,7 +245,7 @@ example18() {
|
||||
// Strings with triple single-quotes or triple double-quotes span
|
||||
// multiple lines and include line delimiters.
|
||||
example19() {
|
||||
print('''Example19 <a href="etc">
|
||||
print('''Example19 <a href="etc">
|
||||
Example19 Don't can't I'm Etc
|
||||
Example19 </a>''');
|
||||
}
|
||||
@ -272,7 +272,7 @@ example20() {
|
||||
class Example21 {
|
||||
List<String> _names;
|
||||
Example21() {
|
||||
_names = ["a", "b"];
|
||||
_names = ["a", "b"];
|
||||
}
|
||||
List<String> get names => _names;
|
||||
set names(List<String> list) {
|
||||
|
@ -292,7 +292,7 @@ calculateArea() ->
|
||||
_ ->
|
||||
io:format("We can only calculate area of rectangles or circles.")
|
||||
end.
|
||||
|
||||
|
||||
% Compile the module and create a process that evaluates `calculateArea` in the
|
||||
% shell.
|
||||
c(calculateGeometry).
|
||||
|
@ -1,5 +1,8 @@
|
||||
---
|
||||
language: PHP
|
||||
contributors:
|
||||
- ["Malcolm Fell", "http://emarref.net/"]
|
||||
- ["Trismegiste", "https://github.com/Trismegiste"]
|
||||
translators:
|
||||
- ["Pascal Boutin", "http://pboutin.net/"]
|
||||
lang: fr-fr
|
||||
|
@ -5,7 +5,7 @@ contributors:
|
||||
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.
|
||||
|
||||
@ -90,7 +90,7 @@ let simplePatternMatch =
|
||||
| _ -> printfn "x is something else" // underscore matches anything
|
||||
|
||||
// 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
|
||||
let validValue = Some(99)
|
||||
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#.
|
||||
|
||||
// ================================================
|
||||
// More on functions
|
||||
// More on functions
|
||||
// ================================================
|
||||
|
||||
// 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
|
||||
// Indentation is needed for each nested module.
|
||||
module FunctionExamples =
|
||||
module FunctionExamples =
|
||||
|
||||
// define a simple adding function
|
||||
let add x y = x + y
|
||||
|
||||
|
||||
// basic usage of a function
|
||||
let a = add 1 2
|
||||
printfn "1+2 = %i" a
|
||||
|
||||
|
||||
// partial application to "bake in" parameters
|
||||
let add42 = add 42
|
||||
let b = add42 1
|
||||
printfn "42+1 = %i" b
|
||||
|
||||
|
||||
// composition to combine functions
|
||||
let add1 = add 1
|
||||
let add2 = add 2
|
||||
let add3 = add1 >> add2
|
||||
let c = add3 7
|
||||
printfn "3+7 = %i" c
|
||||
|
||||
|
||||
// higher order functions
|
||||
[1..10] |> List.map add3 |> printfn "new list is %A"
|
||||
|
||||
|
||||
// lists of functions, and more
|
||||
let add6 = [add1; add2; add3] |> List.reduce (>>)
|
||||
let d = add6 7
|
||||
@ -158,54 +158,54 @@ module FunctionExamples =
|
||||
// ================================================
|
||||
|
||||
// There are three types of ordered collection:
|
||||
// * Lists are most basic immutable collection.
|
||||
// * Arrays are mutable and more efficient when needed.
|
||||
// * Sequences are lazy and infinite (e.g. an enumerator).
|
||||
// * Lists are most basic immutable collection.
|
||||
// * Arrays are mutable and more efficient when needed.
|
||||
// * Sequences are lazy and infinite (e.g. an enumerator).
|
||||
//
|
||||
// Other collections include immutable maps and sets
|
||||
// plus all the standard .NET collections
|
||||
|
||||
module ListExamples =
|
||||
module ListExamples =
|
||||
|
||||
// lists use square brackets
|
||||
// lists use square brackets
|
||||
let list1 = ["a";"b"]
|
||||
let list2 = "c" :: list1 // :: is prepending
|
||||
let list3 = list1 @ list2 // @ is concat
|
||||
|
||||
|
||||
// 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
|
||||
let rec sieve = function
|
||||
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
|
||||
| [] -> []
|
||||
let primes = sieve [2..50]
|
||||
printfn "%A" primes
|
||||
|
||||
printfn "%A" primes
|
||||
|
||||
// pattern matching for lists
|
||||
let listMatcher aList =
|
||||
let listMatcher aList =
|
||||
match aList with
|
||||
| [] -> printfn "the list is empty"
|
||||
| [first] -> printfn "the list has one element %A " first
|
||||
| [first; second] -> printfn "list is %A and %A" first second
|
||||
| _ -> printfn "the list has more than two elements"
|
||||
| [] -> printfn "the list is empty"
|
||||
| [first] -> printfn "the list has one element %A " first
|
||||
| [first; second] -> printfn "list is %A and %A" first second
|
||||
| _ -> printfn "the list has more than two elements"
|
||||
|
||||
listMatcher [1;2;3;4]
|
||||
listMatcher [1;2]
|
||||
listMatcher [1]
|
||||
listMatcher []
|
||||
listMatcher []
|
||||
|
||||
// recursion using lists
|
||||
let rec sum aList =
|
||||
let rec sum aList =
|
||||
match aList with
|
||||
| [] -> 0
|
||||
| x::xs -> x + sum xs
|
||||
sum [1..10]
|
||||
|
||||
// -----------------------------------------
|
||||
// Standard library functions
|
||||
|
||||
// -----------------------------------------
|
||||
|
||||
// Standard library functions
|
||||
// -----------------------------------------
|
||||
|
||||
// map
|
||||
let add3 x = x + 3
|
||||
[1..10] |> List.map add3
|
||||
@ -213,68 +213,68 @@ module ListExamples =
|
||||
// filter
|
||||
let even x = x % 2 = 0
|
||||
[1..10] |> List.filter even
|
||||
|
||||
|
||||
// many more -- see documentation
|
||||
|
||||
module ArrayExamples =
|
||||
|
||||
module ArrayExamples =
|
||||
|
||||
// arrays use square brackets with bar
|
||||
let array1 = [| "a";"b" |]
|
||||
let first = array1.[0] // indexed access using dot
|
||||
|
||||
|
||||
// pattern matching for arrays is same as for lists
|
||||
let arrayMatcher aList =
|
||||
let arrayMatcher aList =
|
||||
match aList with
|
||||
| [| |] -> printfn "the array is empty"
|
||||
| [| first |] -> printfn "the array has one element %A " first
|
||||
| [| first; second |] -> printfn "array is %A and %A" first second
|
||||
| _ -> printfn "the array has more than two elements"
|
||||
| [| |] -> printfn "the array is empty"
|
||||
| [| first |] -> printfn "the array has one element %A " first
|
||||
| [| first; second |] -> printfn "array is %A and %A" first second
|
||||
| _ -> printfn "the array has more than two elements"
|
||||
|
||||
arrayMatcher [| 1;2;3;4 |]
|
||||
|
||||
// Standard library functions just as for List
|
||||
|
||||
[| 1..10 |]
|
||||
|
||||
[| 1..10 |]
|
||||
|> Array.map (fun i -> i+3)
|
||||
|> Array.filter (fun i -> i%2 = 0)
|
||||
|> Array.iter (printfn "value is %i. ")
|
||||
|
||||
|
||||
module SequenceExamples =
|
||||
|
||||
|
||||
module SequenceExamples =
|
||||
|
||||
// sequences use curly braces
|
||||
let seq1 = seq { yield "a"; yield "b" }
|
||||
|
||||
// sequences can use yield and
|
||||
|
||||
// sequences can use yield and
|
||||
// can contain subsequences
|
||||
let strange = seq {
|
||||
// "yield! adds one element
|
||||
yield 1; yield 2;
|
||||
|
||||
|
||||
// "yield!" adds a whole subsequence
|
||||
yield! [5..10]
|
||||
yield! [5..10]
|
||||
yield! seq {
|
||||
for i in 1..10 do
|
||||
for i in 1..10 do
|
||||
if i%2 = 0 then yield i }}
|
||||
// test
|
||||
strange |> Seq.toList
|
||||
|
||||
// test
|
||||
strange |> Seq.toList
|
||||
|
||||
|
||||
// Sequences can be created using "unfold"
|
||||
// Here's the fibonacci series
|
||||
let fib = Seq.unfold (fun (fst,snd) ->
|
||||
Some(fst + snd, (snd, fst + snd))) (0,1)
|
||||
|
||||
// test
|
||||
// test
|
||||
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
|
||||
|
||||
@ -282,33 +282,33 @@ module DataTypeExamples =
|
||||
// -- Use a comma to create a tuple
|
||||
let twoTuple = 1,2
|
||||
let threeTuple = "a",2,true
|
||||
|
||||
|
||||
// Pattern match to unpack
|
||||
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
|
||||
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"}
|
||||
|
||||
// Pattern match to unpack
|
||||
let {First=first} = person1 //sets first="john"
|
||||
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
// Union types (aka variants) have a set of choices
|
||||
// Only case can be valid at a time.
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
|
||||
// Use "type" with bar/pipe to define a union type
|
||||
type Temp =
|
||||
type Temp =
|
||||
| DegreesC of float
|
||||
| DegreesF of float
|
||||
|
||||
|
||||
// Use one of the cases to create one
|
||||
let temp1 = DegreesF 98.6
|
||||
let temp2 = DegreesC 37.0
|
||||
@ -317,29 +317,29 @@ module DataTypeExamples =
|
||||
let printTemp = function
|
||||
| DegreesC t -> printfn "%f degC" t
|
||||
| DegreesF t -> printfn "%f degF" t
|
||||
|
||||
printTemp temp1
|
||||
|
||||
printTemp temp1
|
||||
printTemp temp2
|
||||
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
// Recursive types
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
|
||||
// Types can be combined recursively in complex ways
|
||||
// Types can be combined recursively in complex ways
|
||||
// without having to create subclasses
|
||||
type Employee =
|
||||
type Employee =
|
||||
| Worker of Person
|
||||
| Manager of Employee list
|
||||
|
||||
let jdoe = {First="John";Last="Doe"}
|
||||
let worker = Worker jdoe
|
||||
|
||||
// ------------------------------------
|
||||
|
||||
// ------------------------------------
|
||||
// Modelling with types
|
||||
// ------------------------------------
|
||||
|
||||
// ------------------------------------
|
||||
|
||||
// Union types are great for modelling state without using flags
|
||||
type EmailAddress =
|
||||
type EmailAddress =
|
||||
| ValidEmailAddress of string
|
||||
| InvalidEmailAddress of string
|
||||
|
||||
@ -350,40 +350,40 @@ module DataTypeExamples =
|
||||
|
||||
// The combination of union types and record types together
|
||||
// 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.
|
||||
|
||||
type CartItem = { ProductCode: string; Qty: int }
|
||||
type Payment = Payment of float
|
||||
type ActiveCartData = { UnpaidItems: CartItem list }
|
||||
type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
|
||||
|
||||
type ShoppingCart =
|
||||
|
||||
type ShoppingCart =
|
||||
| EmptyCart // no data
|
||||
| ActiveCart of ActiveCartData
|
||||
| PaidCart of PaidCartData
|
||||
| PaidCart of PaidCartData
|
||||
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
// Built in behavior for types
|
||||
// ------------------------------------
|
||||
// ------------------------------------
|
||||
|
||||
// Core types have useful "out-of-the-box" behavior, no coding needed.
|
||||
// * Immutability
|
||||
// * Pretty printing when debugging
|
||||
// * Equality and comparison
|
||||
// * Serialization
|
||||
|
||||
|
||||
// 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
|
||||
|
||||
// Equality and comparison built in.
|
||||
// Here's an example with cards.
|
||||
type Suit = Club | Diamond | Spade | Heart
|
||||
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
||||
| Nine | Ten | Jack | Queen | King | Ace
|
||||
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
||||
| 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 ]
|
||||
|
||||
// sorting
|
||||
@ -391,27 +391,27 @@ module DataTypeExamples =
|
||||
List.max hand |> printfn "high card is %A"
|
||||
List.min hand |> printfn "low card is %A"
|
||||
|
||||
|
||||
|
||||
// ================================================
|
||||
// Active patterns
|
||||
// ================================================
|
||||
|
||||
module ActivePatternExamples =
|
||||
module ActivePatternExamples =
|
||||
|
||||
// F# has a special type of pattern matching called "active patterns"
|
||||
// where the pattern can be parsed or detected dynamically.
|
||||
// F# has a special type of pattern matching called "active patterns"
|
||||
// where the pattern can be parsed or detected dynamically.
|
||||
|
||||
// "banana clips" are the syntax for active patterns
|
||||
|
||||
|
||||
// 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
|
||||
else if System.Char.IsLetter(ch) then Letter
|
||||
else if System.Char.IsWhiteSpace(ch) then Whitespace
|
||||
else Other
|
||||
else Other
|
||||
|
||||
// ... and then use it to make parsing logic much clearer
|
||||
let printChar ch =
|
||||
let printChar ch =
|
||||
match ch with
|
||||
| Digit -> printfn "%c is a Digit" ch
|
||||
| Letter -> printfn "%c is a Letter" ch
|
||||
@ -424,52 +424,52 @@ module ActivePatternExamples =
|
||||
// -----------------------------------
|
||||
// FizzBuzz using active patterns
|
||||
// -----------------------------------
|
||||
|
||||
|
||||
// You can create partial matching patterns as well
|
||||
// Just use undercore in the defintion, and return Some if matched.
|
||||
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
|
||||
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
|
||||
|
||||
// the main function
|
||||
let fizzBuzz i =
|
||||
let fizzBuzz i =
|
||||
match i with
|
||||
| MultOf3 & MultOf5 -> printf "FizzBuzz, "
|
||||
| MultOf3 -> printf "Fizz, "
|
||||
| MultOf5 -> printf "Buzz, "
|
||||
| MultOf3 & MultOf5 -> printf "FizzBuzz, "
|
||||
| MultOf3 -> printf "Fizz, "
|
||||
| MultOf5 -> printf "Buzz, "
|
||||
| _ -> printf "%i, " i
|
||||
|
||||
|
||||
// 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
|
||||
|
||||
// ------ Example: define sumOfSquares function ------
|
||||
let sumOfSquares n =
|
||||
let sumOfSquares n =
|
||||
[1..n] // 1) take all the numbers from 1 to n
|
||||
|> List.map square // 2) square each one
|
||||
|> List.sum // 3) sum the results
|
||||
|
||||
// test
|
||||
sumOfSquares 100 |> printfn "Sum of squares = %A"
|
||||
|
||||
// ------ Example: define a sort function ------
|
||||
// test
|
||||
sumOfSquares 100 |> printfn "Sum of squares = %A"
|
||||
|
||||
// ------ Example: define a sort function ------
|
||||
let rec sort list =
|
||||
match list with
|
||||
// If the list is empty
|
||||
| [] ->
|
||||
// If the list is empty
|
||||
| [] ->
|
||||
[] // return an empty list
|
||||
// If the list is not empty
|
||||
| firstElem::otherElements -> // take the first element
|
||||
let smallerElements = // extract the smaller elements
|
||||
// If the list is not empty
|
||||
| firstElem::otherElements -> // take the first element
|
||||
let smallerElements = // extract the smaller elements
|
||||
otherElements // from the remaining ones
|
||||
|> List.filter (fun e -> e < firstElem)
|
||||
|> List.filter (fun e -> e < firstElem)
|
||||
|> sort // and sort them
|
||||
let largerElements = // extract the larger ones
|
||||
otherElements // from the remaining ones
|
||||
@ -479,13 +479,13 @@ module AlgorithmExamples =
|
||||
List.concat [smallerElements; [firstElem]; largerElements]
|
||||
|
||||
// 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
|
||||
// ================================================
|
||||
|
||||
module AsyncExample =
|
||||
module AsyncExample =
|
||||
|
||||
// F# has built-in features to help with async code
|
||||
// without encountering the "pyramid of doom"
|
||||
@ -495,23 +495,23 @@ module AsyncExample =
|
||||
open System.Net
|
||||
open System
|
||||
open System.IO
|
||||
open Microsoft.FSharp.Control.CommonExtensions
|
||||
open Microsoft.FSharp.Control.CommonExtensions
|
||||
|
||||
// Fetch the contents of a URL asynchronously
|
||||
let fetchUrlAsync url =
|
||||
async { // "async" keyword and curly braces
|
||||
let fetchUrlAsync url =
|
||||
async { // "async" keyword and curly braces
|
||||
// creates an "async" object
|
||||
let req = WebRequest.Create(Uri(url))
|
||||
use! resp = req.AsyncGetResponse()
|
||||
let req = WebRequest.Create(Uri(url))
|
||||
use! resp = req.AsyncGetResponse()
|
||||
// use! is async assignment
|
||||
use stream = resp.GetResponseStream()
|
||||
use stream = resp.GetResponseStream()
|
||||
// "use" triggers automatic close()
|
||||
// on resource at end of scope
|
||||
use reader = new IO.StreamReader(stream)
|
||||
let html = reader.ReadToEnd()
|
||||
printfn "finished downloading %s" url
|
||||
use reader = new IO.StreamReader(stream)
|
||||
let html = reader.ReadToEnd()
|
||||
printfn "finished downloading %s" url
|
||||
}
|
||||
|
||||
|
||||
// a list of sites to fetch
|
||||
let sites = ["http://www.bing.com";
|
||||
"http://www.google.com";
|
||||
@ -520,7 +520,7 @@ module AsyncExample =
|
||||
"http://www.yahoo.com"]
|
||||
|
||||
// do it
|
||||
sites
|
||||
sites
|
||||
|> List.map fetchUrlAsync // make a list of async tasks
|
||||
|> Async.Parallel // set up the tasks to run in parallel
|
||||
|> Async.RunSynchronously // start them off
|
||||
@ -529,58 +529,58 @@ module AsyncExample =
|
||||
// .NET compatability
|
||||
// ================================================
|
||||
|
||||
module NetCompatibilityExamples =
|
||||
module NetCompatibilityExamples =
|
||||
|
||||
// F# can do almost everything C# can do, and it integrates
|
||||
// seamlessly with .NET or Mono libraries.
|
||||
|
||||
// ------- work with existing library functions -------
|
||||
|
||||
|
||||
let (i1success,i1) = System.Int32.TryParse("123");
|
||||
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
|
||||
|
||||
// ------- Implement interfaces on the fly! -------
|
||||
|
||||
|
||||
// create a new object that implements IDisposable
|
||||
let makeResource name =
|
||||
{ new System.IDisposable
|
||||
let makeResource name =
|
||||
{ new System.IDisposable
|
||||
with member this.Dispose() = printfn "%s disposed" name }
|
||||
|
||||
let useAndDisposeResources =
|
||||
let useAndDisposeResources =
|
||||
use r1 = makeResource "first resource"
|
||||
printfn "using first resource"
|
||||
printfn "using first resource"
|
||||
for i in [1..3] do
|
||||
let resourceName = sprintf "\tinner resource %d" i
|
||||
use temp = makeResource resourceName
|
||||
printfn "\tdo something with %s" resourceName
|
||||
use temp = makeResource resourceName
|
||||
printfn "\tdo something with %s" resourceName
|
||||
use r2 = makeResource "second resource"
|
||||
printfn "using second resource"
|
||||
printfn "done."
|
||||
printfn "using second resource"
|
||||
printfn "done."
|
||||
|
||||
// ------- Object oriented code -------
|
||||
|
||||
|
||||
// F# is also a fully fledged OO language.
|
||||
// It supports classes, inheritance, virtual methods, etc.
|
||||
|
||||
// interface with generic type
|
||||
type IEnumerator<'a> =
|
||||
type IEnumerator<'a> =
|
||||
abstract member Current : 'a
|
||||
abstract MoveNext : unit -> bool
|
||||
abstract MoveNext : unit -> bool
|
||||
|
||||
// abstract base class with virtual methods
|
||||
[<AbstractClass>]
|
||||
type Shape() =
|
||||
type Shape() =
|
||||
//readonly properties
|
||||
abstract member Width : int with get
|
||||
abstract member Height : int with get
|
||||
//non-virtual method
|
||||
member this.BoundingArea = this.Height * this.Width
|
||||
//virtual method with base implementation
|
||||
abstract member Print : unit -> unit
|
||||
abstract member Print : unit -> unit
|
||||
default this.Print () = printfn "I'm a shape"
|
||||
|
||||
// concrete class that inherits from base class and overrides
|
||||
type Rectangle(x:int, y:int) =
|
||||
// concrete class that inherits from base class and overrides
|
||||
type Rectangle(x:int, y:int) =
|
||||
inherit Shape()
|
||||
override this.Width = x
|
||||
override this.Height = y
|
||||
@ -590,20 +590,20 @@ module NetCompatibilityExamples =
|
||||
let r = Rectangle(2,3)
|
||||
printfn "The width is %i" r.Width
|
||||
printfn "The area is %i" r.BoundingArea
|
||||
r.Print()
|
||||
r.Print()
|
||||
|
||||
// ------- extension methods -------
|
||||
|
||||
|
||||
//Just as in C#, F# can extend existing classes with extension methods.
|
||||
type System.String with
|
||||
member this.StartsWithA = this.StartsWith "A"
|
||||
|
||||
//test
|
||||
let s = "Alice"
|
||||
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
||||
|
||||
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
||||
|
||||
// ------- events -------
|
||||
|
||||
|
||||
type MyButton() =
|
||||
let clickEvent = new Event<_>()
|
||||
|
||||
@ -615,11 +615,11 @@ module NetCompatibilityExamples =
|
||||
|
||||
// test
|
||||
let myButton = new MyButton()
|
||||
myButton.OnClick.Add(fun (sender, arg) ->
|
||||
myButton.OnClick.Add(fun (sender, arg) ->
|
||||
printfn "Click event with arg=%O" arg)
|
||||
|
||||
myButton.TestEvent("Hello World!")
|
||||
|
||||
|
||||
```
|
||||
|
||||
## More Information
|
||||
|
@ -51,7 +51,7 @@ function identity(?string $stringOrNull) : ?string
|
||||
class TypeHintedProperties
|
||||
{
|
||||
public ?string $name;
|
||||
|
||||
|
||||
protected int $id;
|
||||
|
||||
private float $score = 100.0;
|
||||
@ -91,7 +91,7 @@ function openBox(Box<int> $box) : int
|
||||
|
||||
|
||||
// Shapes
|
||||
//
|
||||
//
|
||||
// Hack adds the concept of shapes for defining struct-like arrays with a
|
||||
// guaranteed, type-checked set of keys
|
||||
type Point2D = shape('x' => int, 'y' => int);
|
||||
@ -108,7 +108,7 @@ distance(
|
||||
|
||||
|
||||
// Type aliasing
|
||||
//
|
||||
//
|
||||
// Hack adds a bunch of type aliasing features for making complex types readable
|
||||
newtype VectorArray = array<int, Vector<int>>;
|
||||
|
||||
@ -142,7 +142,7 @@ function getRoadType() : RoadType
|
||||
|
||||
|
||||
// Constructor argument promotion
|
||||
//
|
||||
//
|
||||
// To avoid boilerplate property and constructor definitions that only set
|
||||
// properties, Hack adds a concise syntax for defining properties and a
|
||||
// constructor at the same time.
|
||||
@ -171,12 +171,12 @@ class WithoutArgumentPromotion
|
||||
|
||||
|
||||
// Co-operative 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
|
||||
async function cooperativePrint(int $start, int $end) : Awaitable<void>
|
||||
{
|
||||
for ($i = $start; $i <= $end; $i++) {
|
||||
for ($i = $start; $i <= $end; $i++) {
|
||||
echo "$i ";
|
||||
|
||||
// Give other tasks a chance to do something
|
||||
@ -193,9 +193,9 @@ AwaitAllWaitHandle::fromArray([
|
||||
|
||||
|
||||
// Attributes
|
||||
//
|
||||
//
|
||||
// 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
|
||||
<<__Memoize>>
|
||||
@ -248,7 +248,7 @@ class ConsistentBar extends ConsistentFoo
|
||||
class InvalidFooSubclass extends ConsistentFoo
|
||||
{
|
||||
// Not matching the parent constructor will cause a type checker error:
|
||||
//
|
||||
//
|
||||
// "This object is of type ConsistentBaz. It is incompatible with this object
|
||||
// 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
|
||||
// type checker error:
|
||||
//
|
||||
//
|
||||
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
|
||||
// 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
|
||||
|
||||
/ To write multiline content, nest it instead
|
||||
%p
|
||||
%p
|
||||
This is a lot of content that we could probably split onto two
|
||||
separate lines.
|
||||
|
||||
/
|
||||
/
|
||||
You can escape html by using the ampersand and equals sign ( &= ). This
|
||||
converts html-sensitive characters (&, /, :) into their html encoded
|
||||
equivalents. For example
|
||||
@ -102,7 +102,7 @@ $ haml input_file.haml output_file.html
|
||||
/ Inserting Ruby
|
||||
/ -------------------------------------------
|
||||
|
||||
/
|
||||
/
|
||||
To output a Ruby value as the contents of a tag, use an equals sign followed
|
||||
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
|
||||
|
||||
:javascript
|
||||
|
@ -50,9 +50,9 @@ public class LearnJava {
|
||||
System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
|
||||
|
||||
///////////////////////////////////////
|
||||
// Variables
|
||||
// Variables
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
/*
|
||||
* Variable Declaration
|
||||
*/
|
||||
@ -336,29 +336,29 @@ public class LearnJava {
|
||||
|
||||
// toString returns this Object's string representation.
|
||||
System.out.println("trek info: " + trek.toString());
|
||||
|
||||
|
||||
// Double Brace Initialization
|
||||
// The Java Language has no syntax for how to create static Collections
|
||||
// in an easy way. Usually you end up in the following way:
|
||||
|
||||
|
||||
private static final Set<String> COUNTRIES = new HashSet<String>();
|
||||
static {
|
||||
validCodes.add("DENMARK");
|
||||
validCodes.add("SWEDEN");
|
||||
validCodes.add("FINLAND");
|
||||
}
|
||||
|
||||
|
||||
// But there's a nifty way to achive the same thing in an
|
||||
// easier way, by using something that is called Double Brace
|
||||
// Initialization.
|
||||
|
||||
|
||||
private static final Set<String> COUNTRIES = HashSet<String>() {{
|
||||
add("DENMARK");
|
||||
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
|
||||
// is called with the anonymous inner class is created.
|
||||
// This does not only work for Collections, it works for all
|
||||
@ -513,7 +513,12 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
}
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
// Abstract Classes
|
||||
=======
|
||||
|
||||
// Abstract Classes
|
||||
>>>>>>> adambard/master
|
||||
// Abstract Class declaration syntax
|
||||
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
||||
// // Constants and variables
|
||||
@ -528,8 +533,9 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
// unless the method is static, and variables are final by default, unlike an
|
||||
// abstract class. Also abstract classes CAN have the "main" method.
|
||||
|
||||
public abstract class Animal
|
||||
public abstract class Animal
|
||||
{
|
||||
<<<<<<< HEAD
|
||||
public abstract void makeSound();
|
||||
|
||||
// Method can have a body
|
||||
@ -555,10 +561,38 @@ public abstract class Animal
|
||||
{
|
||||
System.out.println("I am abstract");
|
||||
}
|
||||
=======
|
||||
public abstract void makeSound();
|
||||
|
||||
// Method can have a body
|
||||
public void eat()
|
||||
{
|
||||
System.out.println("I am an animal and I am Eating.");
|
||||
// Note: We can access private variable here.
|
||||
age = 30;
|
||||
}
|
||||
|
||||
// No need to initialize, however in an interface
|
||||
// a variable is implicitly final and hence has
|
||||
// to be initialized.
|
||||
private int age;
|
||||
|
||||
public void printAge()
|
||||
{
|
||||
System.out.println(age);
|
||||
}
|
||||
|
||||
// Abstract classes can have main function.
|
||||
public static void main(String[] args)
|
||||
{
|
||||
System.out.println("I am abstract");
|
||||
}
|
||||
>>>>>>> adambard/master
|
||||
}
|
||||
|
||||
class Dog extends Animal
|
||||
{
|
||||
<<<<<<< HEAD
|
||||
// Note still have to override the abstract methods in the
|
||||
// abstract class.
|
||||
@Override
|
||||
@ -580,6 +614,29 @@ class Dog extends Animal
|
||||
pluto.eat();
|
||||
pluto.printAge();
|
||||
}
|
||||
=======
|
||||
// Note still have to override the abstract methods in the
|
||||
// abstract class.
|
||||
@Override
|
||||
public void makeSound()
|
||||
{
|
||||
System.out.println("Bark");
|
||||
// age = 30; ==> ERROR! age is private to Animal
|
||||
}
|
||||
|
||||
// NOTE: You will get an error if you used the
|
||||
// @Override annotation here, since java doesn't allow
|
||||
// overriding of static methods.
|
||||
// What is happening here is called METHOD HIDING.
|
||||
// Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Dog pluto = new Dog();
|
||||
pluto.makeSound();
|
||||
pluto.eat();
|
||||
pluto.printAge();
|
||||
}
|
||||
>>>>>>> adambard/master
|
||||
}
|
||||
|
||||
// Final Classes
|
||||
|
@ -64,7 +64,7 @@ doStuff()
|
||||
// There are three special not-a-real-number values:
|
||||
Infinity; // result of e.g. 1/0
|
||||
-Infinity; // result of e.g. -1/0
|
||||
NaN; // result of e.g. 0/0
|
||||
NaN; // result of e.g. 0/0, stands for 'Not a Number'
|
||||
|
||||
// There's also a boolean type.
|
||||
true;
|
||||
@ -189,7 +189,7 @@ myObj.myFourthKey; // = undefined
|
||||
///////////////////////////////////
|
||||
// 3. Logic and Control Structures
|
||||
|
||||
// The syntax for this section is almost identical to Java's.
|
||||
// The syntax for this section is almost identical to Java's.
|
||||
|
||||
// The `if` structure works as you'd expect.
|
||||
var count = 1;
|
||||
@ -231,8 +231,8 @@ var name = otherName || "default";
|
||||
|
||||
|
||||
// The `switch` statement checks for equality with `===`.
|
||||
// use 'break' after each case
|
||||
// or the cases after the correct one will be executed too.
|
||||
// use 'break' after each case
|
||||
// or the cases after the correct one will be executed too.
|
||||
grade = 'B';
|
||||
switch (grade) {
|
||||
case 'A':
|
||||
@ -516,12 +516,12 @@ more about how to use JavaScript in web pages, start by learning about the
|
||||
[Document Object
|
||||
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
|
||||
|
||||
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
|
||||
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
|
||||
|
||||
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
|
||||
guide of all the counter-intuitive parts of the language.
|
||||
|
||||
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
|
||||
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
|
||||
|
||||
In addition to direct contributors to this article, some content is adapted
|
||||
from Louie Dinh's Python tutorial on this site, and the [JS
|
||||
|
@ -16,7 +16,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
||||
```json
|
||||
{
|
||||
"key": "value",
|
||||
|
||||
|
||||
"keys": "must always be enclosed in double quotes",
|
||||
"numbers": 0,
|
||||
"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]
|
||||
]
|
||||
],
|
||||
|
||||
|
||||
"alternative style": {
|
||||
"comment": "check this out!"
|
||||
, "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.
|
||||
#= 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.
|
||||
=#
|
||||
|
||||
@ -670,7 +670,7 @@ square_area(l) = l * l # square_area (generic function with 1 method)
|
||||
square_area(5) #25
|
||||
|
||||
# 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
|
||||
# Filename: none
|
||||
# Source line: 1 # Prologue
|
||||
@ -703,10 +703,10 @@ code_native(square_area, (Float64,))
|
||||
# vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
|
||||
# pop RBP
|
||||
# ret
|
||||
#
|
||||
#
|
||||
# Note that julia will use floating point instructions if any of the
|
||||
# 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(5) # 78.53981633974483
|
||||
|
||||
@ -737,7 +737,7 @@ code_native(circle_area, (Float64,))
|
||||
# vmulsd XMM0, XMM1, XMM0
|
||||
# pop RBP
|
||||
# ret
|
||||
#
|
||||
#
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
@ -166,7 +166,7 @@ not false # => true
|
||||
|
||||
########################################################################
|
||||
## 3. Functions
|
||||
########################################################################
|
||||
########################################################################
|
||||
|
||||
# Since LiveScript is functional, you'd expect functions to get a nice
|
||||
# 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 `>>`
|
||||
# and `<<` operators, that describe how the flow of values through the
|
||||
# functions.
|
||||
# functions.
|
||||
double-minus-one = (* 2) >> (- 1)
|
||||
double-minus-one = (- 1) << (* 2)
|
||||
|
||||
@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*"
|
||||
## Further reading
|
||||
|
||||
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
|
||||
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:
|
||||
echo "foo" > file0.txt
|
||||
# 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.
|
||||
@ -49,7 +49,7 @@ file2.txt file3.txt: file0.txt file1.txt
|
||||
touch file2.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.
|
||||
|
||||
#-----------------------------------------------------------------------
|
||||
@ -115,7 +115,7 @@ small/%.png: %.svg
|
||||
%.png: %.ps
|
||||
@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.
|
||||
|
||||
# Older makefiles might use suffix rules instead of pattern rules
|
||||
@ -185,7 +185,7 @@ var := hello
|
||||
var2 ::= $(var) hello
|
||||
#:= 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 !
|
||||
|
||||
# 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
|
||||
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!
|
||||
|
||||
@ -97,7 +97,7 @@ or
|
||||
+ Item
|
||||
+ One more item
|
||||
|
||||
or
|
||||
or
|
||||
|
||||
- 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. -->
|
||||
|
||||
Boxes below without the 'x' are unchecked HTML checkboxes.
|
||||
- [ ] First task to complete.
|
||||
- [ ] First task to complete.
|
||||
- [ ] Second task that needs done
|
||||
This checkbox below will be a checked HTML checkbox.
|
||||
- [x] This task has been completed
|
||||
@ -169,7 +169,7 @@ with or without spaces. -->
|
||||
|
||||
***
|
||||
---
|
||||
- - -
|
||||
- - -
|
||||
****************
|
||||
|
||||
<!-- 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
|
||||
[@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.
|
||||
|
||||
%{
|
||||
Multi line comments look
|
||||
Multi line comments look
|
||||
something
|
||||
like
|
||||
this
|
||||
@ -62,10 +62,10 @@ disp('text') % print "text" to the screen
|
||||
% Variables & Expressions
|
||||
myVariable = 4 % Notice Workspace pane shows newly created variable
|
||||
myVariable = 4; % Semi colon suppresses output to the Command Window
|
||||
4 + 6 % ans = 10
|
||||
8 * myVariable % ans = 32
|
||||
2 ^ 3 % ans = 8
|
||||
a = 2; b = 3;
|
||||
4 + 6 % ans = 10
|
||||
8 * myVariable % ans = 32
|
||||
2 ^ 3 % ans = 8
|
||||
a = 2; b = 3;
|
||||
c = exp(a)*sin(pi/2) % c = 7.3891
|
||||
|
||||
% 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
|
||||
% Command syntax:
|
||||
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:
|
||||
[V,D] = eig(A); % this has no equivalent in command form
|
||||
[~,D] = eig(A); % if you only want D and not V
|
||||
@ -103,7 +103,7 @@ a(2) % ans = y
|
||||
|
||||
|
||||
% Cells
|
||||
a = {'one', 'two', 'three'}
|
||||
a = {'one', 'two', 'three'}
|
||||
a(1) % ans = 'one' - returns a cell
|
||||
char(a(1)) % ans = one - returns a string
|
||||
|
||||
@ -113,7 +113,7 @@ A.c = [1 2];
|
||||
A.d.e = false;
|
||||
|
||||
% 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:3) % ans = 32 53
|
||||
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
|
||||
|
||||
% 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
|
||||
% A =
|
||||
|
||||
@ -132,7 +132,7 @@ A = [1 2 3; 4 5 6; 7 8 9]
|
||||
% 7 8 9
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@ -171,7 +171,7 @@ A(1,:) % All columns in row 1
|
||||
% 4 5 42
|
||||
% 7 8 9
|
||||
|
||||
% this is the same as
|
||||
% this is the same as
|
||||
vertcat(A,A);
|
||||
|
||||
|
||||
@ -183,7 +183,7 @@ vertcat(A,A);
|
||||
% 4 5 42 4 5 42
|
||||
% 7 8 9 7 8 9
|
||||
|
||||
% this is the same as
|
||||
% this is the same as
|
||||
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:
|
||||
A one
|
||||
ctranspose(A) % Hermitian transpose the matrix
|
||||
ctranspose(A) % Hermitian transpose the matrix
|
||||
% (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
|
||||
% by a period, they act on each element instead. For example:
|
||||
A * B % Matrix multiplication
|
||||
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.
|
||||
exp(A) % exponentiate each element
|
||||
exp(A) % exponentiate each element
|
||||
expm(A) % calculate the matrix exponential
|
||||
sqrt(A) % take the square root of each element
|
||||
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
|
||||
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
|
||||
plot(x, y)
|
||||
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.
|
||||
% 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
|
||||
set(h, 'Color', 'r')
|
||||
set(h, 'Color', 'r')
|
||||
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
||||
set(h, 'LineStyle', '--')
|
||||
% '--' 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
|
||||
save('myFileName.mat') % Save the variables in your Workspace
|
||||
load('myFileName.mat') % Load saved variables into Workspace
|
||||
save('myFileName.mat') % Save the variables in your Workspace
|
||||
load('myFileName.mat') % Load saved variables into Workspace
|
||||
|
||||
% M-file Scripts
|
||||
% 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).
|
||||
% 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
|
||||
function output = double_input(x)
|
||||
function output = double_input(x)
|
||||
%double_input(x) returns twice the value of x
|
||||
output = 2*x;
|
||||
end
|
||||
double_input(6) % ans = 12
|
||||
double_input(6) % ans = 12
|
||||
|
||||
|
||||
% 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.
|
||||
|
||||
% 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
|
||||
% another function (eg. plot with fplot, evaluate an indefinite integral
|
||||
% anonymous function. Useful when quickly defining a function to pass to
|
||||
% another function (eg. plot with fplot, evaluate an indefinite integral
|
||||
% 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:
|
||||
sqr = @(x) x.^2;
|
||||
@ -336,12 +336,12 @@ doc function_handle % find out more
|
||||
% User input
|
||||
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
|
||||
keyboard
|
||||
|
||||
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
|
||||
fopen(filename)
|
||||
fopen(filename)
|
||||
|
||||
% Output
|
||||
disp(a) % Print out the value of variable a
|
||||
@ -363,8 +363,8 @@ end
|
||||
for k = 1:5
|
||||
disp(k)
|
||||
end
|
||||
|
||||
k = 0;
|
||||
|
||||
k = 0;
|
||||
while (k < 5)
|
||||
k = k + 1;
|
||||
end
|
||||
@ -382,7 +382,7 @@ password = 'root';
|
||||
driver = 'com.mysql.jdbc.Driver';
|
||||
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/
|
||||
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
|
||||
a = fetch(conn, sql) %a will contain your data
|
||||
|
||||
@ -394,7 +394,7 @@ tan(x)
|
||||
asin(x)
|
||||
acos(x)
|
||||
atan(x)
|
||||
exp(x)
|
||||
exp(x)
|
||||
sqrt(x)
|
||||
log(x)
|
||||
log10(x)
|
||||
@ -426,7 +426,7 @@ pinv(A) % calculate the pseudo-inverse
|
||||
zeros(m,n) % m x n matrix of 0's
|
||||
ones(m,n) % m x n matrix of 1's
|
||||
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
|
||||
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
|
||||
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
|
||||
|
||||
% Common vector functions
|
||||
max % largest component
|
||||
min % smallest component
|
||||
max % largest component
|
||||
min % smallest component
|
||||
length % length of a vector
|
||||
sort % sort in ascending order
|
||||
sum % sum of elements
|
||||
sort % sort in ascending order
|
||||
sum % sum of elements
|
||||
prod % product of elements
|
||||
mode % modal value
|
||||
median % median value
|
||||
mean % mean value
|
||||
median % median value
|
||||
mean % mean value
|
||||
std % standard deviation
|
||||
perms(x) % list all permutations of elements of x
|
||||
|
||||
|
@ -47,18 +47,18 @@ void main(string[] args) {
|
||||
// There are no one-value tuples though.
|
||||
// So you can always use () in the mathematical sense.
|
||||
// (string) arg; <- is an error
|
||||
|
||||
|
||||
/*
|
||||
byte: 8 bit signed integer
|
||||
char: 8 bit UTF-8 byte component.
|
||||
short: 16 bit signed integer
|
||||
int: 32 bit signed integer
|
||||
long: 64 bit signed integer
|
||||
|
||||
|
||||
float: 32 bit floating point
|
||||
double: 64 bit floating point
|
||||
real: biggest native size floating point (80 bit on x86).
|
||||
|
||||
|
||||
bool: true or false
|
||||
*/
|
||||
int a = 5;
|
||||
@ -139,14 +139,14 @@ void main(string[] args) {
|
||||
assert !(hewo is s);
|
||||
// same as
|
||||
assert (hewo !is s);
|
||||
|
||||
|
||||
// Allocate arrays using "new array length"
|
||||
int[] integers = new int[] 10;
|
||||
assert(integers.length == 10);
|
||||
assert(integers[0] == 0); // zero is default initializer
|
||||
integers = integers ~ 5; // This allocates a new array!
|
||||
assert(integers.length == 11);
|
||||
|
||||
|
||||
// This is an appender array.
|
||||
// Instead of (length, pointer), it tracks (capacity, length, pointer).
|
||||
// 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 ~= 3;
|
||||
appender.free(); // same as {mem.free(appender.ptr); appender = null;}
|
||||
|
||||
|
||||
// Scope variables are automatically freed at the end of the current scope.
|
||||
scope int[auto~] someOtherAppender;
|
||||
// This is the same as:
|
||||
int[auto~] someOtherAppender2;
|
||||
onExit { someOtherAppender2.free; }
|
||||
|
||||
|
||||
// You can do a C for loop too
|
||||
// - but why would you want to?
|
||||
for (int i = 0; i < 5; ++i) { }
|
||||
@ -178,23 +178,23 @@ void main(string[] args) {
|
||||
assert(i == 5);
|
||||
break; // otherwise we'd go back up to do {
|
||||
}
|
||||
|
||||
|
||||
// This is a nested function.
|
||||
// Nested functions can access the surrounding function.
|
||||
string returnS() { return s; }
|
||||
writeln returnS();
|
||||
|
||||
|
||||
// Take the address of a function using &
|
||||
// The type of a global function is ReturnType function(ParameterTypeTuple).
|
||||
void function() foop = &foo;
|
||||
|
||||
|
||||
// Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
|
||||
string delegate() returnSp = &returnS;
|
||||
writeln returnSp();
|
||||
// Class member functions and struct member functions also fit into delegate variables.
|
||||
// In general, delegates are functions that carry an additional context pointer.
|
||||
// ("fat pointers" in C)
|
||||
|
||||
|
||||
// Allocate a "snapshot" with "new delegate".
|
||||
// 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.
|
||||
@ -232,8 +232,8 @@ void main(string[] args) {
|
||||
auto nestfun = λ() { } // There is NO semicolon needed here!
|
||||
// "}" can always substitute for "};".
|
||||
// This provides syntactic consistency with built-in statements.
|
||||
|
||||
|
||||
|
||||
|
||||
// This is a class.
|
||||
// Note: almost all elements of Neat can be used on the module level
|
||||
// or just as well inside a function.
|
||||
@ -268,7 +268,7 @@ void main(string[] args) {
|
||||
E e = E:cd; // dynamic class cast!
|
||||
e.doE();
|
||||
writeln "$e"; // all interfaces convert to Object implicitly.
|
||||
|
||||
|
||||
// Templates!
|
||||
// Templates are parameterized namespaces, taking a type as a parameter.
|
||||
template Templ(T) {
|
||||
|
@ -5,12 +5,13 @@ contributors:
|
||||
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
|
||||
- ["Yannick Loriot", "https://github.com/YannickL"]
|
||||
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||
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.
|
||||
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
|
||||
// Single-line comments start with //
|
||||
@ -40,15 +41,15 @@ int main (int argc, const char * argv[])
|
||||
|
||||
// Use NSLog to print lines to the console
|
||||
NSLog(@"Hello World!"); // Print the string "Hello World!"
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// Types & Variables
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
// Primitive declarations
|
||||
int myPrimitive1 = 1;
|
||||
long myPrimitive2 = 234554664565;
|
||||
|
||||
|
||||
// Object declarations
|
||||
// Put the * in front of the variable names for strongly-typed object declarations
|
||||
MyClass *myObject1 = nil; // Strong typing
|
||||
@ -56,15 +57,15 @@ int main (int argc, const char * argv[])
|
||||
// %@ is an object
|
||||
// 'description' is a convention to display the value of the Objects
|
||||
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)"
|
||||
|
||||
|
||||
// String
|
||||
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 *mutableString = [NSMutableString stringWithString:@"Hello"];
|
||||
[mutableString appendString:@" World!"];
|
||||
NSLog(@"%@", mutableString); // prints => "Hello World!"
|
||||
|
||||
|
||||
// Character literals
|
||||
NSNumber *theLetterZNumber = @'Z';
|
||||
char theLetterZ = [theLetterZNumber charValue]; // or 'Z'
|
||||
@ -74,11 +75,11 @@ int main (int argc, const char * argv[])
|
||||
NSNumber *fortyTwoNumber = @42;
|
||||
int fortyTwo = [fortyTwoNumber intValue]; // or 42
|
||||
NSLog(@"%i", fortyTwo);
|
||||
|
||||
|
||||
NSNumber *fortyTwoUnsignedNumber = @42U;
|
||||
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
|
||||
NSLog(@"%u", fortyTwoUnsigned);
|
||||
|
||||
|
||||
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
|
||||
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42
|
||||
NSLog(@"%hi", fortyTwoShort);
|
||||
@ -86,7 +87,7 @@ int main (int argc, const char * argv[])
|
||||
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
|
||||
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
|
||||
NSLog(@"%u", fortyOneUnsigned);
|
||||
|
||||
|
||||
NSNumber *fortyTwoLongNumber = @42L;
|
||||
long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42
|
||||
NSLog(@"%li", fortyTwoLong);
|
||||
@ -100,7 +101,7 @@ int main (int argc, const char * argv[])
|
||||
float piFloat = [piFloatNumber floatValue]; // or 3.141592654f
|
||||
NSLog(@"%f", piFloat); // prints => 3.141592654
|
||||
NSLog(@"%5.2f", piFloat); // prints => " 3.14"
|
||||
|
||||
|
||||
NSNumber *piDoubleNumber = @3.1415926535;
|
||||
double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535
|
||||
NSLog(@"%f", piDouble);
|
||||
@ -110,7 +111,7 @@ int main (int argc, const char * argv[])
|
||||
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
|
||||
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
|
||||
// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
|
||||
[oneDecNum decimalNumberByAdding:twoDecNum];
|
||||
[oneDecNum decimalNumberByAdding:twoDecNum];
|
||||
[oneDecNum decimalNumberBySubtracting:twoDecNum];
|
||||
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
|
||||
[oneDecNum decimalNumberByDividingBy:twoDecNum];
|
||||
@ -129,8 +130,8 @@ int main (int argc, const char * argv[])
|
||||
NSArray *anArray = @[@1, @2, @3, @4];
|
||||
NSNumber *thirdNumber = anArray[2];
|
||||
NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3"
|
||||
// NSMutableArray is a mutable version of NSArray, allowing you to change
|
||||
// the items in the array and to extend or shrink the array object.
|
||||
// NSMutableArray is a mutable version of NSArray, allowing you to change
|
||||
// the items in the array and to extend or shrink the array object.
|
||||
// Convenient, but not as efficient as NSArray.
|
||||
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
|
||||
[mutableArray addObject:@"Hello"];
|
||||
@ -160,7 +161,7 @@ int main (int argc, const char * argv[])
|
||||
///////////////////////////////////////
|
||||
// Operators
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
// The operators works like in the C language
|
||||
// For example:
|
||||
2 + 5; // => 7
|
||||
@ -205,13 +206,13 @@ int main (int argc, const char * argv[])
|
||||
NSLog(@"I print");
|
||||
} break;
|
||||
}
|
||||
|
||||
|
||||
// While loops statements
|
||||
int ii = 0;
|
||||
while (ii < 4)
|
||||
{
|
||||
NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
|
||||
} // prints => "0,"
|
||||
} // prints => "0,"
|
||||
// "1,"
|
||||
// "2,"
|
||||
// "3,"
|
||||
@ -221,25 +222,25 @@ int main (int argc, const char * argv[])
|
||||
for (jj=0; jj < 4; jj++)
|
||||
{
|
||||
NSLog(@"%d,", jj);
|
||||
} // prints => "0,"
|
||||
} // prints => "0,"
|
||||
// "1,"
|
||||
// "2,"
|
||||
// "3,"
|
||||
|
||||
// Foreach statements
|
||||
|
||||
// Foreach statements
|
||||
NSArray *values = @[@0, @1, @2, @3];
|
||||
for (NSNumber *value in values)
|
||||
{
|
||||
NSLog(@"%@,", value);
|
||||
} // prints => "0,"
|
||||
} // prints => "0,"
|
||||
// "1,"
|
||||
// "2,"
|
||||
// "3,"
|
||||
|
||||
// Object for loop statement. Can be used with any Objective-C object type
|
||||
for (id item in values) {
|
||||
NSLog(@"%@,", item);
|
||||
} // prints => "0,"
|
||||
for (id item in values) {
|
||||
NSLog(@"%@,", item);
|
||||
} // prints => "0,"
|
||||
// "1,"
|
||||
// "2,"
|
||||
// "3,"
|
||||
@ -250,7 +251,7 @@ int main (int argc, const char * argv[])
|
||||
// Your statements here
|
||||
@throw [NSException exceptionWithName:@"FileNotFoundException"
|
||||
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);
|
||||
} @finally
|
||||
@ -259,17 +260,17 @@ int main (int argc, const char * argv[])
|
||||
} // prints => "Exception: File Not Found on System"
|
||||
// "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];
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// Objects
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
// Create an object instance by allocating memory and initializing it
|
||||
// An object is not fully functional until both steps have been completed
|
||||
MyClass *myObject = [[MyClass alloc] init];
|
||||
|
||||
|
||||
// The Objective-C model of object-oriented programming is based on message
|
||||
// passing to object instances
|
||||
// In Objective-C one does not simply call a method; one sends a message
|
||||
@ -280,7 +281,7 @@ int main (int argc, const char * argv[])
|
||||
|
||||
// End of @autoreleasepool
|
||||
}
|
||||
|
||||
|
||||
// End the program
|
||||
return 0;
|
||||
}
|
||||
@ -301,9 +302,9 @@ int main (int argc, const char * argv[])
|
||||
@interface MyClass : NSObject <MyProtocol> // NSObject is Objective-C's base object class.
|
||||
{
|
||||
// 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)
|
||||
NSString *name;
|
||||
NSString *name;
|
||||
}
|
||||
// Convenient notation for public access variables to auto generate a setter method
|
||||
// By default, setter method name is 'set' followed by @property variable name
|
||||
@ -313,7 +314,7 @@ int main (int argc, const char * argv[])
|
||||
@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor
|
||||
// You can customize the getter and setter names instead of using default 'set' name:
|
||||
@property (getter=lengthGet, setter=lengthSet:) int length;
|
||||
|
||||
|
||||
// Methods
|
||||
+/- (return type)methodSignature:(Parameter Type *)parameterName;
|
||||
|
||||
@ -335,7 +336,7 @@ int main (int argc, const char * argv[])
|
||||
// To access public variables from the implementation file, @property generates a setter method
|
||||
// automatically. Method name is 'set' followed by @property variable name:
|
||||
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
|
||||
[myClass setCount:10];
|
||||
[myClass setCount:10];
|
||||
NSLog(@"%d", [myClass count]); // prints => 10
|
||||
// Or using the custom getter and setter method defined in @interface:
|
||||
[myClass lengthSet:32];
|
||||
@ -358,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell
|
||||
// as a variable
|
||||
// SEL is the data type. @selector() returns a selector from method name provided
|
||||
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
|
||||
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
|
||||
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
|
||||
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
|
||||
// Must put all method arguments into one object to send to performSelector function
|
||||
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
|
||||
@ -382,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
@synthesize roString = _roString; // _roString available now in @implementation
|
||||
|
||||
// Called before calling any class methods or instantiating any objects
|
||||
+ (void)initialize
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self == [MyClass class]) {
|
||||
distance = 0;
|
||||
@ -392,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
// Counterpart to initialize method. Called when an object's reference count is zero
|
||||
- (void)dealloc
|
||||
{
|
||||
[height release]; // If not using ARC, make sure to release class variable objects
|
||||
[height release]; // If not using ARC, make sure to release class variable objects
|
||||
[super dealloc]; // and call parent class dealloc
|
||||
}
|
||||
|
||||
@ -407,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
return self;
|
||||
}
|
||||
// Can create constructors that contain arguments:
|
||||
- (id)initWithDistance:(int)defaultDistance
|
||||
- (id)initWithDistance:(int)defaultDistance
|
||||
{
|
||||
distance = defaultDistance;
|
||||
return self;
|
||||
@ -418,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
return @"Some string";
|
||||
}
|
||||
|
||||
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
|
||||
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
|
||||
{
|
||||
height = defaultHeight;
|
||||
return [[self alloc] init];
|
||||
@ -434,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
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.
|
||||
- (NSNumber *)secretPrivateMethod {
|
||||
return @72;
|
||||
@ -453,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
// Categories
|
||||
///////////////////////////////////////
|
||||
// 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.
|
||||
// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
|
||||
// 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
|
||||
// functionality to an object.
|
||||
// Categories allow you to:
|
||||
// -- Add methods to an existing class for organizational purposes.
|
||||
// -- 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.
|
||||
// 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
|
||||
// -- 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
|
||||
// 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.
|
||||
|
||||
// Here is a simple Car base class.
|
||||
@ -493,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
@end
|
||||
|
||||
// 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
|
||||
// functionality to this existing Car. A good example would be to clean the car. So we would create
|
||||
// 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
|
||||
// a category to add these cleaning methods:
|
||||
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
|
||||
#import "Car.h" // Make sure to import base class to extend.
|
||||
@ -518,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation
|
||||
NSLog(@"Waxed.");
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
|
||||
// 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.
|
||||
@ -533,7 +534,7 @@ int main (int argc, const char * argv[]) {
|
||||
[mustang turnOn]; // Use methods from base Car class.
|
||||
[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.
|
||||
@ -547,7 +548,7 @@ int main (int argc, const char * argv[]) {
|
||||
//To use protected methods, import the category, then implement the methods:
|
||||
#import "Car+Protected.h" // Remember, import in the @implementation file only.
|
||||
|
||||
@implementation Car
|
||||
@implementation Car
|
||||
|
||||
- (void)lockCar {
|
||||
NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
|
||||
@ -570,8 +571,8 @@ int main (int argc, const char * argv[]) {
|
||||
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
|
||||
// @implementation filename: Shape.m
|
||||
#import "Shape.h"
|
||||
// Extensions live in the same file as the class @implementation.
|
||||
@interface Shape () // () after base class name declares an extension.
|
||||
// Extensions live in the same file as the class @implementation.
|
||||
@interface Shape () // () after base class name declares an extension.
|
||||
|
||||
@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
|
||||
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
|
||||
@ -579,7 +580,7 @@ int main (int argc, const char * argv[]) {
|
||||
|
||||
@end
|
||||
// The main @implementation:
|
||||
@implementation Shape
|
||||
@implementation Shape
|
||||
|
||||
@synthesize numOfSides = _numOfSides;
|
||||
|
||||
@ -603,14 +604,14 @@ int main (int argc, const char * argv[]) {
|
||||
@property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
|
||||
- (void)turnOnEngine; // all defined methods.
|
||||
@end
|
||||
// Below is an example class implementing the protocol.
|
||||
// Below is an example class implementing the protocol.
|
||||
#import "CarUtilities.h" // Import the @protocol file.
|
||||
|
||||
@interface Car : NSObject <CarUtilities> // Name of protocol goes inside <>
|
||||
// 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.
|
||||
@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>
|
||||
|
||||
@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
|
||||
@ -619,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.
|
||||
}
|
||||
// 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 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.
|
||||
}
|
||||
|
||||
@end
|
||||
// Instances of Car now have access to the protocol.
|
||||
// Instances of Car now have access to the protocol.
|
||||
Car *carInstance = [[Car alloc] init];
|
||||
[carInstance setEngineOn:NO];
|
||||
[carInstance turnOnEngine];
|
||||
@ -655,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
|
||||
// See the problem is that Sister relies on Brother, and Brother relies on Sister.
|
||||
#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>
|
||||
|
||||
|
||||
- (void)beNiceToSister:(id <Sister>)sister;
|
||||
|
||||
@end
|
||||
@ -667,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
|
||||
///////////////////////////////////////
|
||||
// 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.
|
||||
int (^addUp)(int n); // Declare a variable to store the block.
|
||||
void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
|
||||
int (^addUp)(int n); // Declare a variable to store the block.
|
||||
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
|
||||
// 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.
|
||||
__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.");
|
||||
NSSet *blockSet; // Also, you can declare local variables.
|
||||
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.
|
||||
@implementation BlockExample : NSObject
|
||||
|
||||
@implementation BlockExample : NSObject
|
||||
|
||||
- (void)runBlock:(void (^)(NSString))block {
|
||||
NSLog(@"Block argument returns nothing and takes in a NSString object.");
|
||||
block(@"Argument given to block to execute."); // Calling block.
|
||||
@ -696,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments.
|
||||
///////////////////////////////////////
|
||||
// Memory Management
|
||||
///////////////////////////////////////
|
||||
/*
|
||||
/*
|
||||
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.
|
||||
Objective-C does not use garbage collection and instead uses reference counting. As long as
|
||||
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
|
||||
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
|
||||
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:
|
||||
(1) create the object, (2) use the object, (3) then free the object from memory.
|
||||
With all object interactions, follow the pattern of:
|
||||
(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
|
||||
@ -723,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still
|
||||
|
||||
// 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
|
||||
MyClass *arcMyClass = [[MyClass alloc] init];
|
||||
MyClass *arcMyClass = [[MyClass alloc] init];
|
||||
// ... 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
|
||||
|
||||
// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
|
||||
@ -747,4 +748,8 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not se
|
||||
|
||||
[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf)
|
||||
|
||||
[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html)
|
||||
|
||||
[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)
|
||||
|
||||
[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
|
||||
|
@ -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.
|
||||
|
||||
```
|
||||
$ cat sigtest.ml
|
||||
$ cat sigtest.ml
|
||||
let inc x = x + 1
|
||||
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 add : int -> int -> int
|
||||
val a : int
|
||||
@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;;
|
||||
let sqr2 = sqr (-2) ;;
|
||||
|
||||
(* 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 "()" *)
|
||||
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
|
||||
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.
|
||||
The type system is what makes it so powerful. *)
|
||||
|
||||
@ -320,7 +320,7 @@ let is_one = function
|
||||
;;
|
||||
|
||||
(* Matching predicates, aka "guarded pattern matching". *)
|
||||
let abs x =
|
||||
let abs x =
|
||||
match x with
|
||||
| x when x < 0 -> -x
|
||||
| _ -> x
|
||||
|
@ -7,11 +7,11 @@ contributors:
|
||||
- ["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.
|
||||
|
||||
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/),
|
||||
[the Parrot VM](http://parrot.org/).
|
||||
|
||||
@ -143,7 +143,7 @@ sub with-mandatory-named(:$str!) {
|
||||
say "$str !";
|
||||
}
|
||||
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"
|
||||
|
||||
## 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`.
|
||||
for @array {
|
||||
say "I've got $_";
|
||||
|
||||
|
||||
.say; # This is also allowed.
|
||||
# A dot call with no "topic" (receiver) is sent to `$_` by default
|
||||
$_.say; # the above and this are equivalent.
|
||||
@ -378,8 +378,8 @@ say join(' ', @array[15..*]); #=> 15 16 17 18 19
|
||||
# which is equivalent to:
|
||||
say join(' ', @array[-> $n { 15..$n }]);
|
||||
|
||||
# You can use that in most places you'd expect, even assigning to an array
|
||||
my @numbers = ^20;
|
||||
# You can use that in most places you'd expect, even assigning to an array
|
||||
my @numbers = ^20;
|
||||
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
|
||||
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
|
||||
# only the 15 needed values will be calculated.
|
||||
@ -634,14 +634,14 @@ class A {
|
||||
method get-value {
|
||||
$.field + $!private-field;
|
||||
}
|
||||
|
||||
|
||||
method set-value($n) {
|
||||
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
|
||||
$!field = $n; # This works, because `$!` is always mutable.
|
||||
|
||||
|
||||
$.other-field = 5; # This works, because `$.other-field` is `rw`.
|
||||
}
|
||||
|
||||
|
||||
method !private-method {
|
||||
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 {
|
||||
has $.val;
|
||||
|
||||
|
||||
submethod not-inherited {
|
||||
say "This method won't be available on B.";
|
||||
say "This is most useful for BUILD, which we'll see later";
|
||||
}
|
||||
|
||||
|
||||
method bar { $.val * 5 }
|
||||
}
|
||||
class B is A { # inheritance uses `is`
|
||||
method foo {
|
||||
say $.val;
|
||||
}
|
||||
|
||||
|
||||
method bar { $.val * 10 } # this shadows A's `bar`
|
||||
}
|
||||
|
||||
@ -699,20 +699,20 @@ role PrintableVal {
|
||||
# you "import" a mixin (a "role") with "does":
|
||||
class Item does PrintableVal {
|
||||
has $.val;
|
||||
|
||||
|
||||
# When `does`-ed, a `role` literally "mixes in" the class:
|
||||
# the methods and fields are put together, which means a class can access
|
||||
# the private fields/methods of its roles (but not the inverse !):
|
||||
method access {
|
||||
say $!counter++;
|
||||
}
|
||||
|
||||
|
||||
# However, this:
|
||||
# method print {}
|
||||
# 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() {}`,
|
||||
# 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
|
||||
# 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 ++$n; # lexically-scoped variables are still available
|
||||
}
|
||||
say $Foo::Bar::n; #=> 1
|
||||
@ -1075,8 +1075,8 @@ say [//] Nil, Any, False, 1, 5; #=> False
|
||||
|
||||
|
||||
# Default value examples:
|
||||
say [*] (); #=> 1
|
||||
say [+] (); #=> 0
|
||||
say [*] (); #=> 1
|
||||
say [+] (); #=> 0
|
||||
# meaningless values, since N*1=N and N+0=N.
|
||||
say [//]; #=> (Any)
|
||||
# There's no "default value" for `//`.
|
||||
@ -1335,7 +1335,7 @@ sub MAIN($name) { say "Hello, $name !" }
|
||||
# This produces:
|
||||
# $ perl6 cli.pl
|
||||
# Usage:
|
||||
# t.pl <name>
|
||||
# t.pl <name>
|
||||
|
||||
# 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`
|
||||
@ -1348,7 +1348,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
|
||||
# This produces:
|
||||
# $ perl 6 cli.pl
|
||||
# Usage:
|
||||
# t.pl [--replace] add <key> <value>
|
||||
# t.pl [--replace] add <key> <value>
|
||||
# t.pl remove <key>
|
||||
# t.pl [--as=<Str>] import (File)
|
||||
# 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).
|
||||
.say
|
||||
}
|
||||
|
||||
|
||||
if rand == 0 ff rand == 1 { # compare variables other than `$_`
|
||||
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::$staticVar; // Outputs 'static';
|
||||
|
@ -70,12 +70,12 @@ true && (9 >= 19 || 1 < 2) -- true
|
||||
|
||||
-- Safe access return Maybe a
|
||||
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])
|
||||
last [3,2,1] -- Just (1)
|
||||
-- Random access - indexing
|
||||
[3,4,5,6,7] !! 2 -- Just (5)
|
||||
-- Range
|
||||
-- Range
|
||||
1..5 -- [1,2,3,4,5]
|
||||
length [2,2,2] -- 3
|
||||
drop 3 [5,4,3,2,1] -- [2,1]
|
||||
@ -129,10 +129,10 @@ first :: [Number] -> Number
|
||||
first (x:_) = x
|
||||
first [3,4,5] -- 3
|
||||
second :: [Number] -> Number
|
||||
second (_:y:_) = y
|
||||
second (_:y:_) = y
|
||||
second [3,4,5] -- 4
|
||||
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 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
|
||||
(\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
|
||||
|
||||
-- Currying
|
||||
@ -187,7 +187,7 @@ foldr (+) 0 (1..10) -- 55
|
||||
sum (1..10) -- 55
|
||||
product (1..10) -- 3628800
|
||||
|
||||
-- Testing with predicate
|
||||
-- Testing with predicate
|
||||
any even [1,2,3] -- true
|
||||
all even [1,2,3] -- false
|
||||
|
||||
|
@ -96,7 +96,7 @@ False or True #=> True
|
||||
1 < 2 < 3 # => True
|
||||
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.
|
||||
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
|
||||
@ -256,8 +256,8 @@ empty_dict = {}
|
||||
# Here is a prefilled dictionary
|
||||
filled_dict = {"one": 1, "two": 2, "three": 3}
|
||||
|
||||
# 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.
|
||||
# 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.
|
||||
# Immutable types include ints, floats, strings, tuples.
|
||||
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.
|
||||
@ -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
|
||||
finally: # Execute under all circumstances
|
||||
print("We can clean up resources here")
|
||||
|
||||
|
||||
# Instead of try/finally to cleanup resources you can use a with statement
|
||||
with open("myfile.txt") as f:
|
||||
for line in f:
|
||||
|
@ -36,8 +36,8 @@ head(rivers) # peek at the data set
|
||||
length(rivers) # how many rivers were measured?
|
||||
# 141
|
||||
summary(rivers) # what are some summary statistics?
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 135.0 310.0 425.0 591.2 680.0 3710.0
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 135.0 310.0 425.0 591.2 680.0 3710.0
|
||||
|
||||
# make a stem-and-leaf plot (a histogram-like data visualization)
|
||||
stem(rivers)
|
||||
@ -54,14 +54,14 @@ stem(rivers)
|
||||
# 14 | 56
|
||||
# 16 | 7
|
||||
# 18 | 9
|
||||
# 20 |
|
||||
# 20 |
|
||||
# 22 | 25
|
||||
# 24 | 3
|
||||
# 26 |
|
||||
# 28 |
|
||||
# 30 |
|
||||
# 32 |
|
||||
# 34 |
|
||||
# 26 |
|
||||
# 28 |
|
||||
# 30 |
|
||||
# 32 |
|
||||
# 34 |
|
||||
# 36 | 1
|
||||
|
||||
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 |
|
||||
#
|
||||
# 48 | 1
|
||||
# 50 |
|
||||
# 50 |
|
||||
# 52 | 15578
|
||||
# 54 | 44571222466689
|
||||
# 56 | 023334677000124455789
|
||||
@ -85,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
|
||||
# 74 | 84
|
||||
# 76 | 56
|
||||
# 78 | 4
|
||||
# 80 |
|
||||
# 80 |
|
||||
# 82 | 2
|
||||
|
||||
# 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
|
||||
|
||||
stem(discoveries, scale=2)
|
||||
#
|
||||
#
|
||||
# The decimal point is at the |
|
||||
#
|
||||
# 0 | 000000000
|
||||
@ -122,14 +122,14 @@ stem(discoveries, scale=2)
|
||||
# 8 | 0
|
||||
# 9 | 0
|
||||
# 10 | 0
|
||||
# 11 |
|
||||
# 11 |
|
||||
# 12 | 0
|
||||
|
||||
max(discoveries)
|
||||
# 12
|
||||
summary(discoveries)
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 0.0 2.0 3.0 3.1 4.0 12.0
|
||||
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
||||
# 0.0 2.0 3.0 3.1 4.0 12.0
|
||||
|
||||
# Roll a die a few times
|
||||
round(runif(7, min=.5, max=6.5))
|
||||
@ -262,7 +262,7 @@ class(NULL) # NULL
|
||||
parakeet = c("beak", "feathers", "wings", "eyes")
|
||||
parakeet
|
||||
# =>
|
||||
# [1] "beak" "feathers" "wings" "eyes"
|
||||
# [1] "beak" "feathers" "wings" "eyes"
|
||||
parakeet <- NULL
|
||||
parakeet
|
||||
# =>
|
||||
@ -279,7 +279,7 @@ as.numeric("Bilbo")
|
||||
# =>
|
||||
# [1] NA
|
||||
# Warning message:
|
||||
# NAs introduced by coercion
|
||||
# NAs introduced by coercion
|
||||
|
||||
# Also note: those were just the basic data types
|
||||
# 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
|
||||
# =>
|
||||
# [,1] [,2]
|
||||
# [1,] "1" "dog"
|
||||
# [2,] "2" "cat"
|
||||
# [3,] "3" "bird"
|
||||
# [,1] [,2]
|
||||
# [1,] "1" "dog"
|
||||
# [2,] "2" "cat"
|
||||
# [3,] "3" "bird"
|
||||
# [4,] "4" "dog"
|
||||
class(mat2) # matrix
|
||||
# Again, note what happened!
|
||||
|
@ -285,7 +285,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
|
||||
(= 3 3.0) ; => #t
|
||||
(= 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.
|
||||
;; In other words, it's a simple pointer comparison.
|
||||
(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
|
||||
|
||||
;; `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.
|
||||
;; for other datatypes, `equal?' and `eqv?' return the same result.
|
||||
(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.
|
||||
|
||||
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/System, covers the more basic needs of programming like C can, being closer to the metal.
|
||||
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 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.
|
||||
Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
|
||||
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.
|
||||
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.
|
||||
|
||||
Ready to learn your first Red?
|
||||
|
||||
```
|
||||
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
|
||||
shortcoming of the used lexer but most of the time you start your script or program
|
||||
with the header itself.
|
||||
The header of a red script is the capitalized word "red" followed by a
|
||||
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
|
||||
shortcoming of the used lexer but most of the time you start your script or program
|
||||
with the header itself.
|
||||
The header of a red script is the capitalized word "red" followed by a
|
||||
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
|
||||
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".
|
||||
|
||||
Red []
|
||||
@ -49,21 +49,21 @@ comment {
|
||||
; Your program's entry point is the first executable code that is found
|
||||
; no need to restrict this to a 'main' function.
|
||||
|
||||
; 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
|
||||
; forbidden, because that is how hexadecimal numbers are expressed in Red and
|
||||
; 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
|
||||
; forbidden, because that is how hexadecimal numbers are expressed in Red and
|
||||
; Red/System.
|
||||
|
||||
; assign a value to a variable using a colon ":"
|
||||
my-name: "Red"
|
||||
reason-for-using-the-colon: {Assigning values using the colon makes
|
||||
the equality sign "=" exclusively usable for comparisons purposes,
|
||||
exactly what "=" was intended for in the first place!
|
||||
reason-for-using-the-colon: {Assigning values using the colon makes
|
||||
the equality sign "=" exclusively usable for comparisons purposes,
|
||||
exactly what "=" was intended for in the first place!
|
||||
Remember this y = x + 1 and x = 1 => y = 2 stuff from school?
|
||||
}
|
||||
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.
|
||||
|
||||
prin " My name is " print my-name
|
||||
@ -77,20 +77,20 @@ My name is Red
|
||||
;
|
||||
; Datatypes
|
||||
;
|
||||
; 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
|
||||
; 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
|
||||
; will have a lot of datatypes.
|
||||
; You can recognize types by the exclamation sign at the end. But beware
|
||||
; names ending with an exclamation sign are allowed.
|
||||
; Some of the available types are integer! string! block!
|
||||
; You can recognize types by the exclamation sign at the end. But beware
|
||||
; names ending with an exclamation sign are allowed.
|
||||
; Some of the available types are integer! string! block!
|
||||
|
||||
; Declaring variables before using them?
|
||||
; Red knows by itself what variable is best to use for the data you want to use it
|
||||
; for.
|
||||
; A variable declaration is not always necessary.
|
||||
; Declaring variables before using them?
|
||||
; Red knows by itself what variable is best to use for the data you want to use it
|
||||
; for.
|
||||
; A variable declaration is not always necessary.
|
||||
; It is considered good coding practise to declare your variables,
|
||||
; 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.
|
||||
|
||||
; Variables of integer! type are usually 4 bytes or 32 bits
|
||||
@ -101,7 +101,7 @@ my-integer: 0
|
||||
type? my-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.
|
||||
i2: 1 + i1: 1
|
||||
|
||||
@ -111,9 +111,9 @@ i2 - i1 ; result 1
|
||||
i2 * i1 ; result 2
|
||||
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.
|
||||
; 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
|
||||
|
||||
3 = 2 ; result false
|
||||
@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0)
|
||||
|
||||
;
|
||||
; Control Structures
|
||||
;
|
||||
;
|
||||
; 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.
|
||||
if a < 0 [print "a is negative"]
|
||||
|
||||
; either
|
||||
; 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
|
||||
; 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
|
||||
; be used inside an expression.
|
||||
either a < 0 [
|
||||
either a = 0 [
|
||||
@ -147,7 +147,7 @@ either a < 0 [
|
||||
|
||||
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):
|
||||
|
||||
msg: either a < 0 [
|
||||
@ -162,7 +162,7 @@ msg: either a < 0 [
|
||||
print ["a is " msg lf]
|
||||
|
||||
; 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.
|
||||
c: 5
|
||||
until [
|
||||
@ -172,11 +172,11 @@ until [
|
||||
]
|
||||
; will output:
|
||||
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.
|
||||
|
||||
; 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.
|
||||
c: 5
|
||||
while [c > 0][
|
||||
@ -206,7 +206,7 @@ print twice b ; will output 6.
|
||||
|
||||
## 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).
|
||||
|
||||
@ -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).
|
||||
|
||||
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 combines low-level control over performance with high-level convenience and
|
||||
safety guarantees.
|
||||
Rust combines low-level control over performance with high-level convenience and
|
||||
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.
|
||||
|
||||
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
|
||||
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
|
||||
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.
|
||||
|
||||
Although Rust is a relatively low-level language, Rust has some functional
|
||||
|
@ -5,13 +5,13 @@ contributors:
|
||||
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.
|
||||
|
||||
# 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"
|
||||
@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects.
|
||||
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"
|
||||
(|
|
||||
x <- 20.
|
||||
doubleX = (x: x * 2. self)
|
||||
|)
|
||||
|
||||
"An object which understands all the messages
|
||||
that 'traits point' understands". The parser
|
||||
looks up 'traits point' by sending the messages
|
||||
'traits' then 'point' to a known object called
|
||||
the 'lobby'. It looks up the 'true' object by
|
||||
"An object which understands all the messages
|
||||
that 'traits point' understands". The parser
|
||||
looks up 'traits point' by sending the messages
|
||||
'traits' then 'point' to a known object called
|
||||
the 'lobby'. It looks up the 'true' object by
|
||||
also sending the message 'true' to the lobby."
|
||||
(| parent* = traits point.
|
||||
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.
|
||||
|
||||
```
|
||||
"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)"
|
||||
23 printLine
|
||||
|
||||
"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"
|
||||
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'."
|
||||
'hello' keyOf: 'e' IfAbsent: -1
|
||||
'hello' keyOf: 'e' IfAbsent: -1
|
||||
```
|
||||
|
||||
# Blocks
|
||||
@ -90,13 +90,13 @@ Examples of the use of a block:
|
||||
|
||||
```
|
||||
"returns 'HELLO'"
|
||||
'hello' copyMutable mapBy: [|:c| c capitalize]
|
||||
'hello' copyMutable mapBy: [|:c| c capitalize]
|
||||
|
||||
"returns 'Nah'"
|
||||
'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
|
||||
'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
|
||||
|
||||
"returns 'HaLLO'"
|
||||
'hello' copyMutable mapBy: [|:c|
|
||||
'hello' copyMutable mapBy: [|:c|
|
||||
c = 'e' ifTrue: [c capitalize]
|
||||
False: ['a']]
|
||||
```
|
||||
@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately.
|
||||
|
||||
```
|
||||
"returns An 'E'! How icky!"
|
||||
'hello' copyMutable mapBy: [|:c. tmp <- ''|
|
||||
'hello' copyMutable mapBy: [|:c. tmp <- ''|
|
||||
tmp: c capitalize.
|
||||
tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
|
||||
c capitalize
|
||||
@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t
|
||||
x: 15.
|
||||
"Repeatedly sends 'value' to the first block while the result of sending 'value' to the
|
||||
second block is the 'true' object"
|
||||
[x > 0] whileTrue: [x: x - 1].
|
||||
[x > 0] whileTrue: [x: x - 1].
|
||||
x
|
||||
] 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'.
|
||||
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"
|
||||
(|
|
||||
(|
|
||||
x <- 50.
|
||||
reduceXTo: y = (
|
||||
[x > y] whileTrue: [x: x - 1].
|
||||
[x > y] whileTrue: [x: x - 1].
|
||||
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`.
|
||||
|
||||
|
||||
##Allowable characters:
|
||||
- a-z
|
||||
- A-Z
|
||||
- 0-9
|
||||
##Allowable characters:
|
||||
- a-z
|
||||
- A-Z
|
||||
- 0-9
|
||||
- .+/\*~<>@%|&?
|
||||
- blank, tab, cr, ff, lf
|
||||
|
||||
##Variables:
|
||||
- variables must be declared before use
|
||||
- shared vars must begin with uppercase
|
||||
- local vars must begin with lowercase
|
||||
- variables must be declared before use
|
||||
- shared vars must begin with uppercase
|
||||
- local vars must begin with lowercase
|
||||
- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
|
||||
|
||||
##Variable scope:
|
||||
- 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
|
||||
- Block Temporary: local to a block
|
||||
- Pool: variables in a Dictionary object
|
||||
##Variable scope:
|
||||
- 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
|
||||
- Block Temporary: local to a block
|
||||
- Pool: variables in a Dictionary object
|
||||
- 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
|
||||
- Class: shared with all instances of one class & its subclasses
|
||||
- Class Instance: unique to each instance of a class
|
||||
- Class: shared with all instances of one class & its subclasses
|
||||
- Class Instance: unique to each instance of a class
|
||||
- Instance Variables: unique to each instance
|
||||
|
||||
`"Comments are enclosed in quotes"`
|
||||
@ -53,7 +53,7 @@ Transcript cr. "carriage return / l
|
||||
Transcript endEntry. "flush the output buffer"
|
||||
```
|
||||
|
||||
##Assignment:
|
||||
##Assignment:
|
||||
```
|
||||
| x y |
|
||||
x _ 4. "assignment (Squeak) <-"
|
||||
@ -72,7 +72,7 @@ y := x deepCopy. "copy object and ins
|
||||
y := x veryDeepCopy. "complete tree copy using a dictionary"
|
||||
```
|
||||
|
||||
##Constants:
|
||||
##Constants:
|
||||
```
|
||||
| b |
|
||||
b := true. "true constant"
|
||||
@ -93,7 +93,7 @@ x := #('abc' 2 $a). "mixing of types all
|
||||
|
||||
```
|
||||
|
||||
## Booleans:
|
||||
## Booleans:
|
||||
```
|
||||
| b x y |
|
||||
x := 1. y := 2.
|
||||
@ -132,7 +132,7 @@ b := $A isLowercase. "test if lower case
|
||||
|
||||
```
|
||||
|
||||
## Arithmetic expressions:
|
||||
## Arithmetic expressions:
|
||||
```
|
||||
| x |
|
||||
x := 6 + 3. "addition"
|
||||
@ -190,7 +190,7 @@ x := 100 atRandom. "quick random number
|
||||
|
||||
```
|
||||
|
||||
##Bitwise Manipulation:
|
||||
##Bitwise Manipulation:
|
||||
```
|
||||
| b x |
|
||||
x := 16rFF bitAnd: 16r0F. "and bits"
|
||||
@ -207,7 +207,7 @@ b := 16rFF noMask: 16r0F. "test if all bits se
|
||||
|
||||
```
|
||||
|
||||
## Conversion:
|
||||
## Conversion:
|
||||
```
|
||||
| x |
|
||||
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
|
||||
@ -223,15 +223,15 @@ x := 15 storeStringBase: 16.
|
||||
|
||||
```
|
||||
|
||||
## Blocks:
|
||||
- blocks are objects and may be assigned to a variable
|
||||
- value is last expression evaluated unless explicit return
|
||||
- blocks may be nested
|
||||
- specification [ arguments | | localvars | expressions ]
|
||||
- Squeak does not currently support localvars in blocks
|
||||
- max of three arguments allowed
|
||||
- `^`expression terminates block & method (exits all nested blocks)
|
||||
- blocks intended for long term storage should not contain `^`
|
||||
## Blocks:
|
||||
- blocks are objects and may be assigned to a variable
|
||||
- value is last expression evaluated unless explicit return
|
||||
- blocks may be nested
|
||||
- specification [ arguments | | localvars | expressions ]
|
||||
- Squeak does not currently support localvars in blocks
|
||||
- max of three arguments allowed
|
||||
- `^`expression terminates block & method (exits all nested blocks)
|
||||
- blocks intended for long term storage should not contain `^`
|
||||
|
||||
```
|
||||
| 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"
|
||||
```
|
||||
|
||||
## Method calls:
|
||||
- unary methods are messages with no arguments
|
||||
- binary methods
|
||||
- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
|
||||
- accessing (get/set methods)
|
||||
- testing (boolean tests - is)
|
||||
- comparing (boolean tests with parameter
|
||||
- displaying (gui related methods)
|
||||
- printing (methods for printing)
|
||||
- updating (receive notification of changes)
|
||||
- private (methods private to class)
|
||||
- instance-creation (class methods for creating instance)
|
||||
## Method calls:
|
||||
- unary methods are messages with no arguments
|
||||
- binary methods
|
||||
- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
|
||||
- accessing (get/set methods)
|
||||
- testing (boolean tests - is)
|
||||
- comparing (boolean tests with parameter
|
||||
- displaying (gui related methods)
|
||||
- printing (methods for printing)
|
||||
- updating (receive notification of changes)
|
||||
- private (methods private to class)
|
||||
- instance-creation (class methods for creating instance)
|
||||
```
|
||||
| x |
|
||||
x := 2 sqrt. "unary message"
|
||||
@ -299,7 +299,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr].
|
||||
result := (switch at: $B) value.
|
||||
```
|
||||
|
||||
## Iteration statements:
|
||||
## Iteration statements:
|
||||
```
|
||||
| x y |
|
||||
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"
|
||||
```
|
||||
|
||||
## Character:
|
||||
## Character:
|
||||
```
|
||||
| x y |
|
||||
x := $A. "character assignment"
|
||||
@ -544,7 +544,7 @@ y := x asSet. "convert to set coll
|
||||
```
|
||||
|
||||
## Set: like Bag except duplicates not allowed
|
||||
## IdentitySet: uses identity test (== rather than =)
|
||||
## IdentitySet: uses identity test (== rather than =)
|
||||
```
|
||||
| b x y sum max |
|
||||
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"
|
||||
```
|
||||
|
||||
##Associations:
|
||||
##Associations:
|
||||
```
|
||||
| x y |
|
||||
x := #myVar->'hello'.
|
||||
|
@ -3,7 +3,7 @@ language: swift
|
||||
contributors:
|
||||
- ["Grant Timmerman", "http://github.com/grant"]
|
||||
- ["Christopher Bess", "http://github.com/cbess"]
|
||||
- ["Joey Huang", "http://github.com/kamidox"]
|
||||
- ["Joey Huang", "http://github.com/kamidox"]
|
||||
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||
filename: learnswift.swift
|
||||
---
|
||||
@ -12,7 +12,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D
|
||||
|
||||
The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
|
||||
|
||||
See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift.
|
||||
See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift.
|
||||
|
||||
```swift
|
||||
// import a module
|
||||
@ -74,7 +74,7 @@ if someOptionalString != nil {
|
||||
if someOptionalString!.hasPrefix("opt") {
|
||||
print("has the prefix")
|
||||
}
|
||||
|
||||
|
||||
let empty = someOptionalString?.isEmpty
|
||||
}
|
||||
someOptionalString = nil
|
||||
@ -99,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
|
||||
|
||||
/*
|
||||
Comment here
|
||||
|
||||
|
||||
/*
|
||||
Nested comments are also supported
|
||||
*/
|
||||
@ -298,7 +298,7 @@ print(numbers) // [3, 6, 18]
|
||||
// Structures and classes have very similar capabilites
|
||||
struct NamesTable {
|
||||
let names = [String]()
|
||||
|
||||
|
||||
// Custom subscript
|
||||
subscript(index: Int) -> String {
|
||||
return names[index]
|
||||
@ -329,7 +329,7 @@ public class Shape {
|
||||
|
||||
internal class Rect: Shape {
|
||||
var sideLength: Int = 1
|
||||
|
||||
|
||||
// Custom getter and setter property
|
||||
private var perimeter: Int {
|
||||
get {
|
||||
@ -340,11 +340,11 @@ internal class Rect: Shape {
|
||||
sideLength = newValue / 4
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Lazily load a property
|
||||
// subShape remains nil (uninitialized) until getter called
|
||||
lazy var subShape = Rect(sideLength: 4)
|
||||
|
||||
|
||||
// If you don't need a custom getter and setter,
|
||||
// but still want to run code before and after getting or setting
|
||||
// a property, you can use `willSet` and `didSet`
|
||||
@ -354,19 +354,19 @@ internal class Rect: Shape {
|
||||
print(someIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
init(sideLength: Int) {
|
||||
self.sideLength = sideLength
|
||||
// always super.init last when init custom properties
|
||||
super.init()
|
||||
}
|
||||
|
||||
|
||||
func shrink() {
|
||||
if sideLength > 0 {
|
||||
--sideLength
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override func getArea() -> Int {
|
||||
return sideLength * sideLength
|
||||
}
|
||||
@ -398,13 +398,13 @@ class Circle: Shape {
|
||||
override func getArea() -> Int {
|
||||
return 3 * radius * radius
|
||||
}
|
||||
|
||||
|
||||
// Place a question mark postfix after `init` is an optional init
|
||||
// which can return nil
|
||||
init?(radius: Int) {
|
||||
self.radius = radius
|
||||
super.init()
|
||||
|
||||
|
||||
if radius <= 0 {
|
||||
return nil
|
||||
}
|
||||
@ -458,7 +458,7 @@ enum Furniture {
|
||||
case Desk(height: Int)
|
||||
// Associate with String and Int
|
||||
case Chair(String, Int)
|
||||
|
||||
|
||||
func description() -> String {
|
||||
switch self {
|
||||
case .Desk(let height):
|
||||
@ -497,7 +497,7 @@ protocol ShapeGenerator {
|
||||
|
||||
class MyShape: Rect {
|
||||
var delegate: TransformShape?
|
||||
|
||||
|
||||
func grow() {
|
||||
sideLength += 2
|
||||
|
||||
@ -532,7 +532,7 @@ extension Int {
|
||||
var customProperty: String {
|
||||
return "This is \(self)"
|
||||
}
|
||||
|
||||
|
||||
func multiplyBy(num: Int) -> Int {
|
||||
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
|
||||
such as dynamic strings, lists, and hash tables. The C library also provides
|
||||
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:
|
||||
|
||||
* Convenient cross-platform networking API
|
||||
@ -58,14 +58,14 @@ lighter that that of Lisp, just gets out of the way.
|
||||
#! /bin/env tclsh
|
||||
|
||||
################################################################################
|
||||
## 1. Guidelines
|
||||
## 1. Guidelines
|
||||
################################################################################
|
||||
|
||||
# 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
|
||||
# to get by with syntax they know from another language. It works at first,
|
||||
# but soon leads to frustration with more complex scripts.
|
||||
|
||||
|
||||
# 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,
|
||||
# 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
|
||||
@ -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
|
||||
# character.
|
||||
|
||||
set greeting1 Sal
|
||||
set greeting1 Sal
|
||||
set greeting2 ut
|
||||
set greeting3 ations
|
||||
|
||||
|
||||
#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
|
||||
@ -126,11 +126,11 @@ puts lots\nof\n\n\n\n\n\nnewlines
|
||||
set somevar {
|
||||
This is a literal $ sign, and this \} escaped
|
||||
brace remains uninterpreted
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# In a word enclosed in double quotes, whitespace characters lose their special
|
||||
# meaning
|
||||
# meaning
|
||||
set name Neo
|
||||
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,
|
||||
@ -193,8 +193,8 @@ set greeting "Hello $people::person1::name"
|
||||
namespace delete ::
|
||||
|
||||
|
||||
# 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
|
||||
# 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
|
||||
# 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.
|
||||
namespace eval people {
|
||||
@ -210,7 +210,7 @@ set people::person1::name Neo
|
||||
|
||||
|
||||
################################################################################
|
||||
## 4. Commands
|
||||
## 4. Commands
|
||||
################################################################################
|
||||
|
||||
# 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
|
||||
set amounts 10\ 33\ 18
|
||||
set amounts 10\ 33\ 18
|
||||
set amount [lindex $amounts 1]
|
||||
|
||||
|
||||
@ -339,7 +339,7 @@ eval {set name Neo}
|
||||
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}
|
||||
lappend command {Archibald Sorbisol}
|
||||
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.
|
||||
set replacement {Archibald Sorbisol}
|
||||
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 \
|
||||
{set name Archibald Sorbisol}
|
||||
|
||||
@ -364,12 +364,12 @@ eval $command ;# The same error as before: too many arguments to "set" in \
|
||||
# command.
|
||||
set replacement [list {Archibald Sorbisol}]
|
||||
set command {set name $replacement}
|
||||
set command [subst $command]
|
||||
set command [subst $command]
|
||||
eval $command
|
||||
|
||||
|
||||
# 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.
|
||||
|
||||
|
||||
@ -422,12 +422,12 @@ proc while {condition script} {
|
||||
|
||||
# The "coroutine" command creates a separate call stack, along with a command
|
||||
# to enter that call stack. The "yield" command suspends execution in that
|
||||
# stack.
|
||||
# stack.
|
||||
proc countdown {} {
|
||||
#send something back to the initial "coroutine" command
|
||||
yield
|
||||
|
||||
set count 3
|
||||
set count 3
|
||||
while {$count > 1} {
|
||||
yield [incr count -1]
|
||||
}
|
||||
@ -435,12 +435,12 @@ proc countdown {} {
|
||||
}
|
||||
coroutine countdown1 countdown
|
||||
coroutine countdown2 countdown
|
||||
puts [countdown 1] ;# -> 2
|
||||
puts [countdown 2] ;# -> 2
|
||||
puts [countdown 1] ;# -> 1
|
||||
puts [countdown 1] ;# -> 0
|
||||
puts [countdown 1] ;# -> 2
|
||||
puts [countdown 2] ;# -> 2
|
||||
puts [countdown 1] ;# -> 1
|
||||
puts [countdown 1] ;# -> 0
|
||||
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
|
||||
' tutorial, you'll understand what it all means.
|
||||
Console.Title = ("Learn X in Y Minutes")
|
||||
Console.WriteLine("NAVIGATION") 'Display
|
||||
Console.WriteLine("NAVIGATION") 'Display
|
||||
Console.WriteLine("")
|
||||
Console.ForegroundColor = ConsoleColor.Green
|
||||
Console.WriteLine("1. Hello World Output")
|
||||
@ -39,13 +39,13 @@ Module Module1
|
||||
Case "2" 'Hello Input
|
||||
Console.Clear()
|
||||
HelloWorldInput()
|
||||
Case "3" 'Calculating Whole Numbers
|
||||
Case "3" 'Calculating Whole Numbers
|
||||
Console.Clear()
|
||||
CalculatingWholeNumbers()
|
||||
Case "4" 'Calculting Decimal Numbers
|
||||
Case "4" 'Calculting Decimal Numbers
|
||||
Console.Clear()
|
||||
CalculatingDecimalNumbers()
|
||||
Case "5" 'Working Calcculator
|
||||
Case "5" 'Working Calcculator
|
||||
Console.Clear()
|
||||
WorkingCalculator()
|
||||
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
|
||||
'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()
|
||||
'Title of Console Application
|
||||
Console.Title = "Hello World Ouput | Learn X in Y Minutes"
|
||||
@ -172,7 +172,7 @@ Module Module1
|
||||
'program more than once.
|
||||
Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes"
|
||||
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: ")
|
||||
Dim a As Double = Console.ReadLine
|
||||
Console.Write("Second number: ")
|
||||
@ -192,7 +192,7 @@ Module Module1
|
||||
Console.WriteLine(" = " + f.ToString.PadLeft(3))
|
||||
Console.ReadLine()
|
||||
'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)")
|
||||
'The program grabs the variable and prints and starts again.
|
||||
answer = Console.ReadLine
|
||||
@ -208,8 +208,8 @@ Module Module1
|
||||
|
||||
Console.Title = "Using For Loops | Learn X in Y Minutes"
|
||||
'Declare Variable and what number it should count down in Step -1,
|
||||
'Step -2, Step -3 ect.
|
||||
For i As Integer = 10 To 0 Step -1
|
||||
'Step -2, Step -3 ect.
|
||||
For i As Integer = 10 To 0 Step -1
|
||||
Console.WriteLine(i.ToString) 'Print the value of the counter
|
||||
Next i 'Calculate new value
|
||||
Console.WriteLine("Start") 'Lets start the program baby!!
|
||||
@ -274,8 +274,8 @@ End Module
|
||||
|
||||
## 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.
|
||||
It starts with a declaration, informing some metadata (optional).
|
||||
|
||||
|
||||
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
|
||||
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.
|
||||
That's what the parser will retrieve from the XML file.
|
||||
Elements appear between the open and close tags. -->
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- Below, an element with two attributes -->
|
||||
<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,
|
||||
using document definitions, such as DTD and XML Schema.
|
||||
|
||||
A XML document which follows a document definition is called valid,
|
||||
regarding that document.
|
||||
A XML document which follows a document definition is called valid,
|
||||
regarding that document.
|
||||
|
||||
With this tool, you can check the XML data outside the application logic.
|
||||
|
||||
```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.-->
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
Loading…
Reference in New Issue
Block a user