Tuesday, 31 July 2012

Partial & Tagged Literals

Partial

Partial is a great function. The doc (doc partial) describes it as taking function f and fewer than the normal arguments to f. What is returned is a function that a variable number of remainder args. There are many potential applications and allow you to essentially create duplicate but similar functions without code duplication.

(def only-strings (partial filter string?))
(only-strings ["first test" :anothertest 3 4 "last test"])
("first test" "last test")

Tagged Literals

I mentioned a tagged literal in my last post. Namely the #inst "2012" part. That convenience is a tagged literal for creating a date. I accidently noticed there's a new one in the build i've done from github. That's the #uuid which seems to have appeared from 1.4-alpha4. It appears there aren't many available beyond that yet but they're definitely worth keeping an eye on as they're very handy. Hopefully at some point i'll do a post on creating your own.

Sunday, 29 July 2012

Focusing on Clojure

Back on Numbers

Numbers can be appended with letters that allow you to specify the type.

(type 1000)
java.lang.Long

(type 1000N)
clojure.lang.BigInt

(type 1000M)
clojure.lang.BigDecimal

Map, Reduce & Filter

These healthy staples allow you to apply functions to sequences. The usage is dependant on context. I'll go through each one:

Map

Map applies a function to a sequence of data and returns a sequence of the same length with the function applied to each

(map (fn [n] (* n 10)) '(1 2 3 4 5 6 7 8 9 10))
(10 20 30 40 50 60 70 80 90 100)

Functions with multiple arity can also be used. The result of this function is multiplying arg 1 with arg 2. This has given us a list of square numbers.

(map (fn [n m] (* n m)) (range 1 11) (range 1 11))
(1 4 9 16 25 36 49 64 81 100)

Reduce

Reduce is similar however instead of returning a list of the same size, the goal is to get to a single result. So arg 1 and arg 2 are used in combination to produce a single result, which then becomes arg 1 and #3 becomes arg 2. This is best shown with an example.

(reduce * (range 1 6))
120

To produce that output the following is equivalent:
((((1 * 2) * 3) * 4) * 5) * 6 = 120

Filter

Filter is again similar, however the size of the output is variable. You could end up with a list as long as the original or empty or anywhere in between. Filter works by providing a predicate function with the list and outputs the values of the list where the function returns a truthy value.

(filter even? (range 1 11))
(2 4 6 8 10)

ArrayList

Since clojure is on the JVM, it can work with java code seemlessly

(def x (java.util.ArrayList.))
(map #(.add x %) (range 1 11))
(true true true true true true true true true true)
x
#<ArrayList [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>

Sequential destructuring

Vectors can be sequentially destructured as demonstrated here

(def x [5 10 [3 5] 99.9])
[5 10 [3 5] 99.9]
(let [[a b _] x] (+ a b))
15

The & can also be used

(let [[a & rest] x] rest)
[10 [3 5] 99.9]

Date

Just as a quick reference, #inst "" can be used for quick date creation

(def d #inst "2012")
#inst "2012-01-01T00:00:00.000-00:00"
(type d)
java.util.Date

Repeatedly Partial

Lookup these values

(take 15 (repeatedly (partial rand-int 60)))
(48 18 41 4 41 49 45 22 0 25 17 57 45 36 52)

Others

Some other useful functions found are memoize, doseq, dotimes, for, range, doc, find-doc and source.

Thursday, 26 July 2012

Clojure revisit

Well, it appears i've forgotton all my clojure knowledge. The only thing I appear to have remembered is the thinking style behind it all. So, after reviewing some basics today let's write them down.

Getting to the REPL

java -cp clojure-1.4.0.jar clojure.main

Basic Math

(+ 1 2 3)
(- 3 2 1)
(/ 1 2 3)
(* 1 2 3)

Numbers

Numbers can be represented infinitely appended with an M or as ratio's.
2r10110110 ; this is radix 2 (bin)
8r755 ; this is radix 8 (oct)
16rFFF ; this is radix 16 (hex)

Types

There are many forms of types available in clojure
nil ; equivalent to null essentially, it is neither true or false
true false ; these are boolean values :fred ; this is a symbol
\c \newline \space \tab ; these are chars
"string" ; this is a string literal
(1 2 3) ; this is a list
[1 2 3] ; this is a vector
{:a 1 :b 2 :c 3} ; this is a map
#{:a :b :c} ; this is a set
^{:a 1}[1 2 3] ; this is a vector with metadata

Functions

Functions are defined with the fn function, however this creates anonymous functions and to store them you need to use defn
(defn average [x y] (/ (+ x y) 2))

Useful functions

Just some I remember from last time

  • (zipmap [:a :b :c] [1 2 3])
    {:c 3, :b 2, :a 1}
  • (doc zipmap)
    ; prints current documentation
  • (source zipmap)
    ; prints source
  • (cons :y [:a :b :c])
    [:y :a :b :c]

In my next post about clojure I want to include some stuff about map, reduce and filter.

Friday, 13 July 2012

Starting an new Activity

Before starting a new activity from a current one, you need to setup the classes.

Intent display = new Intent(this, DisplayMessageActivity.class);
EditText editText = findViewById(R.id.edit_text);
String message = editText.getText().toString();
display.putExtra(EXTRA_MESSAGE, message);
startActivity(display);

From the DisplayMessageActivity then, you can get the extra like this.

Intent intent = getIntent();
String message = intent.getStringExtra(PreviousActivityClassname.EXTRA_MESSAGE);

Thursday, 12 July 2012

Android UI Weight

Android weights are like drink mixes, "2 parts vodka, 1 part coffee liqueur". If you set one widget to a weight of 2 and another to a weight of 1 - the first will get 2/3rds of the space and the other will get 1/3rd.
When using weights, it's a good idea to set the layout_width to 0 to improve performance. It improves performance because it doesn't need to work out something that ultimately is irrelevant.

Tuesday, 10 July 2012

Design Patterns

Some I can think of off the top of my head:

  • Subscriber
  • Builder
  • Singleton
  • Adapter
  • Factory
  • Facade

Patterns can be broken down into five types, four of which were described in gang of four. The fifth has been added later but its contents predate many of the other patterns. They are
  1. Creational Patterns
  2. Structural Patterns
  3. Behavioural Patterns
  4. Concurrency Patterns
  5. Architectural Patterns

Creational Patterns

So this includes Abstract Factory, Builder, Factory Method, Lazy Initialisation, Multiton Pattern, Object Pool, Prototype and Singleton

Structural Patterns

Adapter, Bridge, Composite, Decorator, Facade, Front Controller, Flyweight, Proxy and Module

Behavioural Patterns

Blackboard, Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Momento, Null Object, Observer, Servant, Specification, State, Strategy, Template method and Visitor

Concurrency Patterns

Active Object, Balking, Message Design, Double-checked Locking, Event-based asynchronous, Guarded Suspension, Lock, Monitor Object, Reactor, Read-Write Lock, Scheduler, Thread Pool and Thread-Specific Storage

Architectural Patterns

SOA, MVC, N-Tier, Event Driven, Peer-to-Peer et al

As each pattern could be its own post, i won't attempt to describe them here but will work through the list as individual posts

Monday, 9 July 2012

Makefile

Before we can have a useful makefile, we should first create some files that the build tool can be run against.

module.h

#include

void sample_func();

module.c

#include "module.h"

void sample_func() {
    printf("Hello World!");
}

main.c

#include "module.h"

void sample_func();

int main() {
    sample_func();
    return 0;
}

So, now we have a directory with 3 files. A module which includes a header and source file. And a main source file that includes an entry point and has a dependency on our module. Let's make a Makefile for this.

GCC = gcc
FLAGS = -O2 -j3
CC = ${GCC} ${FLAGS}

all: main.o module.o
  ${CC} main.o module.o -o target_bin
main.o: main.c module.h
  ${CC} -I . -c main.c
module.o: module.c module.h
  ${CC} -I . -c module.c
clean:
  rm -rf *.o
  rm target_bin