package main
import (
"io";
"fmt";
"os";
"strings";
)
func main() {
// read the file in bytes array
b, err := io.ReadFile("readfile.go");
if err!=nil {
fmt.Println("error on read file");
os.Exit(-1);
}
// convert from bytes to string
strbuffer := string(b);
// split into lines
lines := strings.Split(strbuffer, "\n", 0);
// iterate each
for i, line := range lines {
fmt.Printf("%d: %s\n", i, line);
}
}
all about go, ruby, python, perl, java, scala, osgi, RCP computing, network, hacking, security, encryption. and other interesting stuff
Posts mit dem Label tutorial werden angezeigt. Alle Posts anzeigen
Posts mit dem Label tutorial werden angezeigt. Alle Posts anzeigen
Samstag, 28. November 2009
read a file and print the count of lines
Freitag, 27. November 2009
strings package in golang
package main
import (
"strings";
"fmt";
)
func main() {
data := "bla blu blub";
fmt.Println(data);
// return: bla blu blub
// convert string in bytes
b := strings.Bytes(data);
fmt.Println(b); // print every byte as array
// return: [98 108 97 32 98 108 117 32 98 108 117 98]
// test if the string begin with the prefix
if strings.HasPrefix(data, "bl") {
fmt.Println("data: \"", data, "\" begin with the prefix \"bl\"");
}
// test if the string end with the suffix
if strings.HasSuffix(data, "blub") {
fmt.Println("data: \"", data, "\" end with \"blub\"");
}
// Index returns the index of the first instance of sep in s,
// or -1 if sep is not present in s.
fmt.Println("index: ", strings.Index(data, "blu"));
// return: index: 4
fmt.Println("index: ", strings.Index(data, "b"));
// return: index: 0
fmt.Println("last index: ", strings.LastIndex(data, "b"));
// return: last index: 11
// LastIndex return the last occurency of seeking string
// with Repeat you can repeat ;)
fmt.Println("r: ", strings.Repeat("x", 10));
// return: r: xxxxxxxxxx
// split the string in array of string
as := strings.Split("root:alsdfjl:230:/blub/blub:lalalala", ":", 0);
fmt.Println(as);
// return: [root alsdfjl 230 /blub/blub lalalala]
fmt.Println(strings.Join(as, "|"));
// return: root|alsdfjl|230|/blub/blub|lalalala
fmt.Println(strings.ToLower("UASFalsdfuADSFWE$$"));
// return: uasfalsdfuadsfwe$$
fmt.Println(strings.ToUpper("owenadsfoadsfj"));
// return: OWENADSFOADSFJ
fmt.Println("<", strings.TrimSpace(" asdf sdowe "), ">");
// return: < asdf sdowe >
}
base64 in golang
package main
import (
"encoding/base64";
"bytes";
"fmt";
)
func main() {
// create the buffer
bb := &bytes.Buffer{};
bbURL := &bytes.Buffer{};
// create two base64 encoder (standard and for url)
encoder := base64.NewEncoder(base64.StdEncoding, bb);
encoderURL := base64.NewEncoder(base64.URLEncoding, bbURL);
data := "hallo this is a test, a=23&var2=blabla+-?!%$/\\";
fmt.Println("data : ", data);
// to encode data, use Write([]bytes),
// therefore you must convert string to bytes
// with string.Bytes(d string)
encoder.Write([]byte(data));
encoder.Close();
encoderURL.Write([]byte(data));
encoderURL.Close();
// voila
fmt.Println("encoded Std: ", bb.String());
fmt.Println("encoded URL: ", bbURL.String());
}
Mittwoch, 25. November 2009
time in go
package main
import "fmt"
import "time"
func main() {
fmt.Println("time in seconds : ", time.Seconds());
fmt.Println("time in nanoseconds: ", time.Nanoseconds());
fmt.Println("sleep 1 second.");
time.Sleep(1*1000*1000*1000);
fmt.Println("time in seconds : ", time.Seconds());
fmt.Println("time in nanoseconds: ", time.Nanoseconds());
fmt.Println("wait sleep 1 second.");
before := time.Nanoseconds();
time.Sleep(1*1000*1000*1000);
after := time.Nanoseconds();
fmt.Println("difference of nanoseconds: ", (after-before));
t:=time.LocalTime();
fmt.Println("time.String(): ", t.String());
}
time.Seconds() get the time as unix time in seconds
time.Nanoseconds() dito
time.Sleep(x) sleep for x nanoseconds
to sleep 1 second do time.Sleep(1e9)
to get any type back from function
let look:
package main
import "fmt"
import "rand"
import "time"
func my() interface{} {
rand.Seed(time.Nanoseconds()/1000000);
switch rand.Intn(3) {
case 0: var i int; i=4; return i;
case 1: var f float; f=2.3; return f;
case 2: var s string; s="blub"; return s;
}
var b byte;
b='c';
return b;
}
func main() {
fmt.Println(my());
time.Sleep(1e9);
fmt.Println(my());
time.Sleep(1e9);
fmt.Println(my());
time.Sleep(1e9);
fmt.Println(my());
time.Sleep(1e9);
fmt.Println(my());
}
with func my() interface{} {...} we declare a function which return an interface. This is a void interface, which can implement all types. Thus we can back every typ back. The my() function simple init the rand and get randomly different types back.
Dienstag, 24. November 2009
golang networking
a simple get for http:
ok, it was not very simple.
r, _, err := http.Get("http://www.google.com/robots.txt");
get the Response in r. Response has: a StatusCode, Body and Header.
Header is a simple string hash. Body is an interface to ReadCloser: all structures with Read and Close.
func Get(url string) (r *Response, finalURL string, err os.Error) is doing followings:
- do a redirection loop (maximal 10 times)
- parse the url
- send the request
- if should redirect, get the new location in header
- if should not redirect: return the result from send()
b, err = io.ReadAll(r.Body);
read the data from response body (which has a reader from connection) in a byte array.
fmt.Println(string(b));
printout the bytes as string
create a simple webserver
http.Handle("/hello", http.HandlerFunc(HelloServer));
set the hadler function HelloServer with "/hello".
err := http.ListenAndServe(":8080", nil);
start the TCP server on port 8080, that handle the registered handler.
io.WriteString(c, "hello, world!\n"); write a simple string.
http.ServeFile(c, req, "myhtml.html"); read the file and print it out.
package main
import (
"io";
"strings";
"log";
"http";
"fmt";
)
func main() {
r, _, err := http.Get("http://www.google.com/robots.txt");
var b []byte;
if err == nil {
b, err = io.ReadAll(r.Body);
r.Body.Close();
}
if err != nil {
log.Stderr(err)
} else {
fmt.Println(string(b));
}
}
ok, it was not very simple.
r, _, err := http.Get("http://www.google.com/robots.txt");
get the Response in r. Response has: a StatusCode, Body and Header.
type Response struct {
Status string; // e.g. "200 OK"
StatusCode int; // e.g. 200
Header map[string]string;
Body io.ReadCloser;
}
Header is a simple string hash. Body is an interface to ReadCloser: all structures with Read and Close.
func Get(url string) (r *Response, finalURL string, err os.Error) is doing followings:
- do a redirection loop (maximal 10 times)
- parse the url
- send the request
- if should redirect, get the new location in header
- if should not redirect: return the result from send()
b, err = io.ReadAll(r.Body);
read the data from response body (which has a reader from connection) in a byte array.
fmt.Println(string(b));
printout the bytes as string
create a simple webserver
package main
import (
"http";
"io";
)
// hello world, the web server
func HelloServer(c *http.Conn, req *http.Request) {
io.WriteString(c, "hello, world!\n");
}
// call a html page
func MyServerPage(c *http.Conn, req *http.Request) {
http.ServeFile(c, req, "myhtml.html");
}
func main() {
http.Handle("/hello", http.HandlerFunc(HelloServer));
http.Handle("/my.html", http.HandlerFunc(MyServerPage));
err := http.ListenAndServe(":8080", nil);
if err != nil {
panic("ListenAndServe: ", err.String())
}
}
http.Handle("/hello", http.HandlerFunc(HelloServer));
set the hadler function HelloServer with "/hello".
err := http.ListenAndServe(":8080", nil);
start the TCP server on port 8080, that handle the registered handler.
io.WriteString(c, "hello, world!\n"); write a simple string.
http.ServeFile(c, req, "myhtml.html"); read the file and print it out.
Samstag, 21. November 2009
learning go
so there will be some golang tips.
create a struct with three variables, a and b are integers. name is a string. The struct name is My.
m:= XXX{inputs} create and initialize the struct to variable m.
Println(m) print out: {1 2 ray}.
to create you own methods for the stuct do: func (v *Mystruct) method(...) returntyps { ... }
here we create the String() method for printing our struct as a string. Access variables are done through m.var.
to define a simple array of integers: a:=[3]int{1,2,3}
if you don't know the length: a:=[]int{1,2,3,4,5,1,2,3}
create an assoziative array or dictionary or hash: hash := map[string]int{"eins":1, "zwei":2, "drei":3}; where map[keytyp]valuetyp.
print out:
key: blub value: aodu
key: ouew value: gofdu
key: a value: ousdf
Read a directory:
let look the source on src/pkg/io/utils.go:
func ReadDir(dirname string) ([]*os.Dir, os.Error) : ReadDir reads the directory named by dirname and returns a list of sorted directory entries.
func Open(name string, flag int, perm int) (file *File, err Error): Open opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. It returns the File and an Error, if any.
Open return a File pointer. internal Open called a syscall to open
func (file *File) Readdir(count int) (dirs []Dir, err Error): Readdir reads the contents of the directory associated with file and returns an array of up to count Dir structures, as would be returned by Stat, in directory order. Subsequent calls on the same file will yield further Dirs. A negative count means to read until EOF. Readdir returns the array and an Error, if any.
our io.ReadDir() open the dir, read it through the file, create a list, sort and return the dir list.
print out all direcotries name.
more info about dir is in: src/pkg/os/types.go or http://golang.org/pkg/os/#Dir
Read a file
type My struct {
a, b int;
name string;
}
create a struct with three variables, a and b are integers. name is a string. The struct name is My.
m := My{1,2,"ray"};
fmt.Println(m);
m:= XXX{inputs} create and initialize the struct to variable m.
Println(m) print out: {1 2 ray}.
to create you own methods for the stuct do: func (v *Mystruct) method(...) returntyps { ... }
func (m *My) String() string {
ret := fmt.Sprintf("a: %d, b: %d, name: %s\n", m.a, m.b, m.name);
return ret;
}
here we create the String() method for printing our struct as a string. Access variables are done through m.var.
to define a simple array of integers: a:=[3]int{1,2,3}
if you don't know the length: a:=[]int{1,2,3,4,5,1,2,3}
create an assoziative array or dictionary or hash: hash := map[string]int{"eins":1, "zwei":2, "drei":3}; where map[keytyp]valuetyp.
hash2 := map[string]string{"blub":"aodu", "a":"ousdf", "ouew":"gofdu"};
// iterate through the hash, range return the key and value of the hash.
for k, v := range hash2 {
fmt.Println("key: ",k," value: ",v);
}
print out:
key: blub value: aodu
key: ouew value: gofdu
key: a value: ousdf
Read a directory:
package main
import (
"io";
"fmt";
)
func main() {
dir, err := io.ReadDir("/home/ray/daten");
fmt.Println("err: ", err);
fmt.Println(dir);
for _, v := range dir {
fmt.Println(">>", v);
}
}
let look the source on src/pkg/io/utils.go:
// ReadDir reads the directory named by dirname and returns
// a list of sorted directory entries.
func ReadDir(dirname string) ([]*os.Dir, os.Error) {
f, err := os.Open(dirname, os.O_RDONLY, 0); // open you directory
if err != nil {
return nil, err
}
list, err := f.Readdir(-1); // f is a file handler
f.Close();
if err != nil {
return nil, err
}
dirs := make(dirList, len(list));
for i := range list {
dirs[i] = &list[i]
}
sort.Sort(dirs);
return dirs, nil;
}
func ReadDir(dirname string) ([]*os.Dir, os.Error) : ReadDir reads the directory named by dirname and returns a list of sorted directory entries.
func Open(name string, flag int, perm int) (file *File, err Error): Open opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. It returns the File and an Error, if any.
Open return a File pointer. internal Open called a syscall to open
func (file *File) Readdir(count int) (dirs []Dir, err Error): Readdir reads the contents of the directory associated with file and returns an array of up to count Dir structures, as would be returned by Stat, in directory order. Subsequent calls on the same file will yield further Dirs. A negative count means to read until EOF. Readdir returns the array and an Error, if any.
our io.ReadDir() open the dir, read it through the file, create a list, sort and return the dir list.
for _, v := range dir {
if v.IsDirectory() {
fmt.Println(v.Name," is directory");
}
}
print out all direcotries name.
more info about dir is in: src/pkg/os/types.go or http://golang.org/pkg/os/#Dir
Read a file
fileObj, err := os.Open( "echo.go", os.O_RDONLY, 0666 );
if err != nil {
log.Stderr( err );
return;
}
//open the file and test for errors. log.Stderr print the message with a timestamp as a log.
// create a buffered reader
r := bufio.NewReader( fileObj );
// read each line
for {
line, err := r.ReadString('\n');
Dienstag, 17. November 2009
some go libraries
| Package | Purpose | Examples |
| fmt | formatted I/O | Printf, Sprintf |
| os | OS interface | Open, Read, Write |
| strconv | numbers <-> strings | Atoi, Atof, Itoa |
| io | generic I/O | Copy, Pipe |
| flag | flags: --help etc. | Bool, String |
| log | event logging | Log, Logf, Stderr |
| regexp | regular expressions | Compile, Match |
| template | HTML, etc. | Parse, Execute |
| bytes | byte arrays | Compare, Buffer |
further libs: bignum, crypto, encoding, exec, hash, http, image, json, net, math, rand, regexp, sort, syscall, xml, time, unicode,
go pakcages
package is a collection of source files begining with "package nameofpackage".
each package can have an init() for initalization data (single threaded).
let see:
a.go
b.go
mainab.go
output:
at first there will be called init. later the main.
"To build a program, the packages, and the files within them, must be compiled in the correct order.
Package dependencies determine the order in which to build packages. "
import "fmt"
// now useable fmt outputs
fmt.Print(...)
import my "fmt" // with my own name. (for purpose if namespace coliders ;)
my.Print(...)
each package can have an init() for initalization data (single threaded).
let see:
a.go
package a
import "fmt"
var A int
func init() {
A = 4;
fmt.Print("A init\n");
}
b.go
package b
import "fmt"
var B int
func init() {
B=15;
fmt.Print("B init\n");
}
mainab.go
package main
import (
"fmt";
"./a";
"./b";
)
func main() {
fmt.Print("call main()\n");
var x= a.A;
var y= b.B;
var z = x + y;
fmt.Print(z);
}
output:
./6.out
B init
A init
call main()
at first there will be called init. later the main.
"To build a program, the packages, and the files within them, must be compiled in the correct order.
Package dependencies determine the order in which to build packages. "
defer in go
"The defer statement executes a function (or method)
when the enclosing function returns. The arguments
are evaluated at the point of the defer; the function
call happens upon return." GocourseDay1.pdf
leet look folowing programm:
a() call with defer b(). But the outprint show:
we can see that b() will be called before a() return.
=> defer is useful for closing fds, unlocking mutexes, etc.
defer is simmilar to atexit() for main() in C.
futher example:
the output is:
as we can see: defer f1(f2()) f2() is called immediately but f1() is called at ending.
when the enclosing function returns. The arguments
are evaluated at the point of the defer; the function
call happens upon return." GocourseDay1.pdf
leet look folowing programm:
package main
import "fmt"
func b() {
fmt.Printf("called b()\n");
}
func a() int {
fmt.Printf("start a()\n");
defer b();
fmt.Printf("ended a()\n");
return 0;
}
func main() {
fmt.Printf("start main\n");
fmt.Printf("call a()\n");
a();
fmt.Printf("after a()\n");
fmt.Printf("\n");
}
a() call with defer b(). But the outprint show:
./6.out
start main
call a()
start a()
ended a()
called b()
after a()
we can see that b() will be called before a() return.
=> defer is useful for closing fds, unlocking mutexes, etc.
defer is simmilar to atexit() for main() in C.
futher example:
package main
import "fmt"
func trace(s string) string {
fmt.Print("entering:", s, "\n");
return s
}
func un(s string) {
fmt.Print("leaving:", s, "\n")
}
func a() {
defer un(trace("a"));
fmt.Print("in a\n")
}
func b() {
defer un(trace("b"));
fmt.Print("in b\n");
a()
}
func main() { b() }
the output is:
./6.out
entering:b
in b
entering:a
in a
leaving:a
leaving:b
as we can see: defer f1(f2()) f2() is called immediately but f1() is called at ending.
further go
Go doesn't have references.
all private functions begin with small character.
all public functions begin with big character.
To generate some Unit test:
name: mylib_test.go ( xxx_test.go )
the function must be called: TestXXX(t *testing.T) { ...
and import: "testing"
send Fatal error
The T struct is:
There are some functions XXXf are with format string
Fail(), Failed(): set the failed variable or ask them. (don't exit)
FailNow() set the fail and exit.
Log()/Logf(): set the errors string.
Error()/Errorf(): Log with Fail
Fatal()/Fatalf(): Log with FailNow
To test a package, write a set of Go source files
within the same package; give the files names of the
form *_test.go.
testing tool: gotest
func TestXxxx(t *testing.T)
create the file. later call gotest my_test.go
all private functions begin with small character.
all public functions begin with big character.
To generate some Unit test:
name: mylib_test.go ( xxx_test.go )
the function must be called: TestXXX(t *testing.T) { ...
and import: "testing"
send Fatal error
if err != nil {
t.Fatalf("Myerror %q: %s", path, err)
}
// or
t.Errorf("bla bla %q ", path)
The T struct is:
type T struct {
errors string;
failed bool;
ch chan *T;
}
There are some functions XXXf are with format string
Fail(), Failed(): set the failed variable or ask them. (don't exit)
FailNow() set the fail and exit.
Log()/Logf(): set the errors string.
Error()/Errorf(): Log with Fail
Fatal()/Fatalf(): Log with FailNow
To test a package, write a set of Go source files
within the same package; give the files names of the
form *_test.go.
testing tool: gotest
func TestXxxx(t *testing.T)
create the file. later call gotest my_test.go
Montag, 16. November 2009
trapped go
we create first a file (package) Person
Person.go:
then the main package with main()
Main.go
compile and link:
6g Person.go
6g Main.go
6l -o Main Main.6
execute: ./Main
>person is:
>Name: blub Vorname: blue
At first we must import our file as "./Person"
At second the function that are created for outside must begin with Capitalized Character.
Person.newPerson(...) doesnot work.
"For clients (importers) of the package, names must
be upper case to be visible: global variables,
functions, types, constants, plus methods and
structure fields for global variables and types.
const hello = "you smell" // package visible
const Hello = "you smell nice" // globally visible
const _Bye = "stinko!" // _ is not upper
"
Person.go:
package Person
type Person struct {
vorname string;
name string;
alter int;
}
func NewPerson(v string, n string, a int) *Person {
return &Person{v, n, a}
}
func (pers *Person) String() string {
return "Name: "+pers.name+" Vorname: "+pers.vorname;
}
then the main package with main()
Main.go
package main
import (
prs "./Person";
"fmt";
)
func main() {
person := prs.NewPerson("blue", "blub", 42);
fmt.Printf("person is: \n");
fmt.Printf(person.String());
fmt.Printf("\n");
}
compile and link:
6g Person.go
6g Main.go
6l -o Main Main.6
execute: ./Main
>person is:
>Name: blub Vorname: blue
At first we must import our file as "./Person"
At second the function that are created for outside must begin with Capitalized Character.
package Person
type Person struct {
vorname string;
name string;
alter int;
}
func newPerson(v string, n string, a int) *Person {
return &Person{v, n, a}
}
Person.newPerson(...) doesnot work.
"For clients (importers) of the package, names must
be upper case to be visible: global variables,
functions, types, constants, plus methods and
structure fields for global variables and types.
const hello = "you smell" // package visible
const Hello = "you smell nice" // globally visible
const _Bye = "stinko!" // _ is not upper
"
Sonntag, 15. November 2009
Go
Here is some introduction to new Google programing language.
At first go has his design to build a fast compiling system programming language for fast application. There is no mess with Java or C#/C++. go has no inheritance, but interfaces.
simple tutorial can be found on golang.org
At first the question: why yet another language?
google need a language which is fast in compiling and runing. Has the advantages of typing but not overloaded wiht oop stuff.
simple example:
as you has see variables are defined with var
for printing is there the package fmt: fmt.Printf(..)
then exists other methods as in C.
to compile:
x64:
6g file.go
6l file.6 -o file
for x86
8g file.go
8l file.8 -o file
to be continued ...
...
At first go has his design to build a fast compiling system programming language for fast application. There is no mess with Java or C#/C++. go has no inheritance, but interfaces.
simple tutorial can be found on golang.org
At first the question: why yet another language?
google need a language which is fast in compiling and runing. Has the advantages of typing but not overloaded wiht oop stuff.
simple example:
// define the namespace
package main
// import the formated print package
// import fmt "fmt";
// import a couple of packages
import (
"flag"; // flag package is a good replacament for main(int argc, char **args) and
// replace the argument calculation with getopt() and switch. then create
// a help function automatic.
"fmt";
)
// create a boolean variable from package flag and set the values
var blub = flag.Bool("g", false, "blub lubn blub")
// g => -g
// false => set it at first to false
// "blub..." => description in help switch
func main() {
flag.Parse();
// parse the arguments
// ask if the
if *blub {
fmt.Printf("blub was setted\n");
} else {
fmt.Printf("blub was not setted\n");
}
}
as you has see variables are defined with var
var v1 int;
var v2 string;
var v3 float;
for printing is there the package fmt: fmt.Printf(..)
then exists other methods as in C.
to compile:
x64:
6g file.go
6l file.6 -o file
for x86
8g file.go
8l file.8 -o file
to be continued ...
...
Dienstag, 6. Oktober 2009
learning Scala 3
this tutorial based on:
http://www.artima.com/scalazine/articles/steps.html
def max(x: Int, y: Int) -> define a function, with 2 parameters (integer)
: Int -> return is integer.
if (x < y) y else x -> function body
greet save a Unit -> a function
create an array with 3 strings
important indexes are in brakes () not square brackets[]
http://www.artima.com/scalazine/articles/steps.html
def max(x: Int, y: Int): Int = if (x < y) y else x
def max(x: Int, y: Int) -> define a function, with 2 parameters (integer)
: Int -> return is integer.
if (x < y) y else x -> function body
scala> def greet() = println("Hello, world!")
greet: ()Unit
scala> greet()
Hello, world!
scala> greet
Hello, world!
greet save a Unit -> a function
args.foreach(arg => println(arg))
args.foreach((arg: String) => println(arg))
args.foreach(println)
for (arg <- args)
println(arg)
scala> for (i <- 0 to 5)
| println(i)
0
1
2
3
4
5
val greetStrings: Array[String] = new Array[String](3)
create an array with 3 strings
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"
important indexes are in brakes () not square brackets[]
for (i <- 0 to 2)
print(greetStrings(i))
learning Scala 2
this tutorial based on:
http://www.thomasknierim.com/104/scala/scala-tutorial-1/
http://www.thomasknierim.com/104/scala/scala-tutorial-2/
http://www.thomasknierim.com/104/scala/scala-tutorial-3/
for(val arg: String <- args) -> an array into each arg as String
similar: args.foreach(arg => println("Hello" + arg + "!"))
"=>" that can be read “with a given argument this do that”
args.foreach(println)
(x: Int) => x - 1 -> anonymous function declaration
var decrease = (x: Int) => x – something
something is not defined yet. decrease is depend on context -> clousure
In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context.
something = 10
decrease(100)
some examples for higher-order functions
List("alpha", "beta", "crash") -> create a list
map() -> map each list element to some condition/function
p => p.substring(0,1) p is the element p.substring(0,1) is the function
_ -> ist the element (similar to perl $_ )
(_*2) is equivalent to (i => i * 2)
let look:
new java.io.File(".") use the java api and create a file object File.
listFiles is the same as listFiles() in java. in scala you don't need brakes.
for (file <- filesHere; if matcher(file.getName))
yield file
iterate all filesHere (files in path "."). if name match to query, yield the file. the file get in an array.
define different functions
filesMatching(matcher: String => Boolean)
define the function with a matcher(String) which return Boolean
http://www.thomasknierim.com/104/scala/scala-tutorial-1/
http://www.thomasknierim.com/104/scala/scala-tutorial-2/
http://www.thomasknierim.com/104/scala/scala-tutorial-3/
object Hello {
def main(args: Array[String]) {
for(val arg: String <- args)
System.out.println("Hello, " + arg + "!");
}
}
for(val arg: String <- args) -> an array into each arg as String
similar: args.foreach(arg => println("Hello" + arg + "!"))
"=>" that can be read “with a given argument this do that”
args.foreach(println)
var decrease = (x: Int) => x - 1
decrease(11)
(x: Int) => x - 1 -> anonymous function declaration
var decrease = (x: Int) => x – something
something is not defined yet. decrease is depend on context -> clousure
In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context.
something = 10
decrease(100)
some examples for higher-order functions
scala> List("alpha", "beta", "crash").map(
p => p.substring(0,1))
res0: List[java.lang.String] = List(a, b, c)
scala> List(1, 2, 3) map (_ * 2)
res1: List[Int] = List(2, 4, 6)
scala> List("Tango", "Mango", "Bobo", "Gogo")
map (_.endsWith("go"))
res2: List[Boolean] = List(true, true, false, true)
List("alpha", "beta", "crash") -> create a list
map() -> map each list element to some condition/function
p => p.substring(0,1) p is the element p.substring(0,1) is the function
_ -> ist the element (similar to perl $_ )
(_*2) is equivalent to (i => i * 2)
object FileMatcher {
private val filesHere=(new java.io.File(".")).listFiles
private def filesMatching(matcher: String => Boolean)=
for (file <- filesHere; if matcher(file.getName))
yield file
def filesEnding(query: String)=
filesMatching(_.endsWith(query))
def filesContaining(query: String)=
filesMatching(_.contains(query))
def filesRegex(query: String)=
filesMatching(_.matches(query))
}
object Main {
def main(args: Array[String]) {
val query = args(0);
var matchingFiles = FileMatcher.filesEnding(query)
matchingFiles = FileMatcher.filesContaining(query)
matchingFiles = FileMatcher.filesRegex(query)
}
}
let look:
scala> (new java.io.File(".")).listFiles
res2: Array[java.io.File] = Array(./FrenchDate$.class, ./FrenchDate.class, ./Complex.scala, ./s1.class, ./s1$.class, ./FrenchDate.scala, ./Timer$$anonfun$main$1.class, ./s1.scala, ./Timer$.class, ./Hello.class, ./ComplexNumbers.class, ./Hello.scala, ./Hello$$anonfun$main$1.class, ./blog_scala2.txt, ./Timer.class, ./Hello$.class, ./Complex.class, ./blog_scala1.txt, ./ComplexNumbers.sca...
new java.io.File(".") use the java api and create a file object File.
listFiles is the same as listFiles() in java. in scala you don't need brakes.
for (file <- filesHere; if matcher(file.getName))
yield file
iterate all filesHere (files in path "."). if name match to query, yield the file. the file get in an array.
scala> var matchingFiles = FileMatcher.filesEnding(query)
matchingFiles: Array[java.io.File] = Array(./Complex.scala, ./FrenchDate.scala, ./s1.scala, ./Hello.scala, ./Main.scala, ./ComplexNumbers.scala, ./Timer.scala)
def filesEnding(query: String)=
filesMatching(_.endsWith(query))
define different functions
filesMatching(matcher: String => Boolean)
define the function with a matcher(String) which return Boolean
learning Scala
This tutorial based on:
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://www.thomasknierim.com/77/scala/scala-tutorial-2/
write a file s1.scala
object -> declare a static singleton object
args: Array[String] -> a variable args as Array of Strings
compile and execute
you get created standard java class files, but you must use java interpreter with setted parameters.
As you can see, the scala executable is a simple shell script, which start the java virtual machine with specific parameters and the scala library.
Create Date.scala
In scala is everything an object. There is no primitive datatypes (that is similar to ruby).
Because scala based on functional programming functions are objects too.
with functions as object you can very simple code a callback.
rather the function timeFlies() you can use anonymous functions ala:
oncePerSecond(() => println("time flies like an arrow..."))
"() => code" declare an anonymous function
Clases:
define class Complex with two arguments,
def re() and im() are getters. return type of these two methods is not given explicitly
if you have no arguments in function, write: def re = real
class Complex(real: Double, imaginary: Double) -> primary constructor, which is part of the class declaration
override -> for overriding functions
(if (im < 0) "" else "+") have you see it ;)
require(denominator != 0) -> look that variable is not null, throw exception
def this(n: Int) = this(n, 1) -> create from Rational(2) -> Rational(2,1)
you can see +-*/ are objects functions, which can be simple overrided
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://www.thomasknierim.com/77/scala/scala-tutorial-2/
write a file s1.scala
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
object -> declare a static singleton object
args: Array[String] -> a variable args as Array of Strings
compile and execute
$ scalac s1.scala
$ ls
s1.class s1$.class s1.scala
you get created standard java class files, but you must use java interpreter with setted parameters.
$ java s1
Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
at java.lang.ClassLoader.defineClass1(Native Method)
....
$ file /usr/bin/scala
$ /usr/bin/scala: POSIX shell script text executable
$ cat /usr/bin/scala
#!/bin/sh
JAVA_DIR=/usr/share/java
LIB_CLASSPATH=$JAVA_DIR/scala-library.jar:$JAVA_DIR/scala-compiler.jar:$JAVA_DIR/jline.jar
exec ${JAVACMD:=java} ${JAVA_OPTS:=-Xmx256M -Xms16M} \
-Xbootclasspath/a:$LIB_CLASSPATH \
-classpath .:$CLASSPATH:$LIB_CLASSPATH \
scala.tools.nsc.MainGenericRunner \
"$@"
$ scala s1
hallo
As you can see, the scala executable is a simple shell script, which start the java virtual machine with specific parameters and the scala library.
Create Date.scala
import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate {
def main(args: Array[String]) {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
}
| import java.util.{Date, Locale} | import Date and Locale from java.util |
| import java.text.DateFormat._ | DateFormat._ is similar to DateFormat.* in java |
| val | declare an inmutable variable |
| val now = new Date | simmilar to "Date now = new Date();" in java |
| println(df format now) | "df format now" is similar to "df.format(now)" |
In scala is everything an object. There is no primitive datatypes (that is similar to ruby).
Because scala based on functional programming functions are objects too.
object Timer {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
with functions as object you can very simple code a callback.
| timeFlies() | our callback function. |
| callback: () => Unit | parameter for a function. ()=>Unit is the type of all functions which take no arguments and return nothing. |
| Thread sleep 1000 | is similar to Thread.sleep(1000) |
rather the function timeFlies() you can use anonymous functions ala:
oncePerSecond(() => println("time flies like an arrow..."))
"() => code" declare an anonymous function
Clases:
class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}
define class Complex with two arguments,
def re() and im() are getters. return type of these two methods is not given explicitly
object ComplexNumbers {
def main(args: Array[String]) {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
}
if you have no arguments in function, write: def re = real
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
class Complex(real: Double, imaginary: Double) -> primary constructor, which is part of the class declaration
override -> for overriding functions
(if (im < 0) "" else "+") have you see it ;)
class Rational(numerator: Int, denominator: Int) {
require(denominator != 0)
private val gcd = greatestCommonDivisor(numerator.abs,
denominator.abs)
val n = numerator / gcd
val d = denominator / gcd
def this(n: Int) = this(n, 1)
private def greatestCommonDivisor(a: Int, b: Int): Int =
if (b == 0) a else greatestCommonDivisor(b, a % b)
def + (that: Rational): Rational =
new Rational(n * that.d + d * that.n, d * that.d)
def - (that: Rational): Rational =
new Rational(n * that.d - d * that.n, d * that.d)
def * (that: Rational): Rational =
new Rational(n * that.n, d * that.d)
def / (that: Rational): Rational =
new Rational(n * that.d, d * that.n)
override def toString = n + "/" + d
}
require(denominator != 0) -> look that variable is not null, throw exception
def this(n: Int) = this(n, 1) -> create from Rational(2) -> Rational(2,1)
you can see +-*/ are objects functions, which can be simple overrided
Abonnieren
Posts (Atom)