Thursday, October 31, 2013

Erlang: Truncate a Floating Point Number to N Decimal Places

An Erlang function to truncate a floating point number to N decimal places ignoring trailing zeros.

%% Truncates a floating point number F to N decimal places ignoring trailing zeros.
-spec trunc(float()|integer(), integer()) -> float().
trunc(F, N) ->
Prec = math:pow(10, N),
1> c(ql).

2> ql:trunc(3.1415926525, 4).

3> ql:trunc(3.1400, 4).

4> ql:trunc(3.0, 4).

5> ql:trunc(3, 4).

Tuesday, October 29, 2013

Pipe Input from stdin to an Erlang Program

Below is an Erlang program which read integers from the standard input and outputs them in reverse order. escript provides scripting support for short Erlang programs which can also take command line arguments.
#!/usr/bin/env escript

r(L) ->
case io:fread("", "~d") of
eof ->
io:format("Reverse List: ~p~n", [L]),
{ok, [N]} ->

main(_) -> r([]).
I have inputs in a file in.txt.
To pass it the Erlang program we can use the pipe | operator with cat.
cat in.txt | escript hr.erl
This will produce the output
Reverse List: [2,1,0,6,5,4]
It is a normal practice to use the redirection operator < to send input as stdin taken from a file. But for some reasons, it's not working as intended with Erlang programs. The above program does not terminate if used with the redirection operator. It's the same case when using the command erl -noshell -s hr main < in.txt with exported module and function main/0. Of course, Erlang is not meant to be used like this. But still, it would be nice if we could. So finally pipe to the rescue. Instead of redirection, use pipe to send in input, which works correctly.

Sunday, October 27, 2013

Erlang List Comprehension with Multiple Generators

I was a bit lost with the permutation example from the Erlang docs. The post by Peter Miller helped. Anyway, here is my explanation on its working.

Generate permutations of all elements in a list.
perms([]) -> [[]];
perms(L) -> [[H|T] || H <- L, T <- perms(L -- [H])].
Let's say it's in a module named test. Compile and load it. Call it will the list [1,2,3].
1> test:perms([1,2,3]).
To understand this let us look at list comprehension. Single generators are straight forward.
2> [X || X <- lists:seq(1, 5)].
Read it as, X such that X is generated from a list with sequence 1 to 5. Let us consider list comprehension with multiple generators.
3> [{X, Y} || X <- [1,2,3], Y <- [10,11,12]].
Here we are constructing a tuple {X, Y} such that X is generated from list [1,2,3] and Y is generated from the list [10,11,12]. We can see the pairing from the generated list of tuples. It takes the first element from the first list and combines it with each individual element from the second list, then takes the second element from the first list and combines with all elements from the second list and so on recursively. Constructing a list. A non-empty list has a head and a tail. So we can represent a list as [H|T].
4> hd([1]).
5> tl([1]).
6> [ 1 | [] ].
7> [ 1 | [2,3] ].
8> [H|T] = [1,2,3].
9> H.
10> T.
Let's write down the reduction steps.
perms([]) = [ [] ].

perms([1]) = [ 1 | [] ]
= [ [1] ].
% produce a list with head as 1 and tail generated from the list obtained from
% the permutation of the original list without the current head.
= [ [1|T] || T <- perms([2]) ]
= [ [1|[2]] ]
= [ [1, 2] ]
% produce a list with head as 2 and tail generated from the list obtained from
% the permutation of the original list without the current head.
= [ [2|T] || T <- perms([1]) ]
= [ [2|[1]] ]
= [ [2, 1] ]
Combining both we get,
perms([1,2]) = [ [[1|T] || T <- perms([2])],
[[2|T] || T <- perms([1])] ].

= [ [[1|T] || T <- [[2]]],
[[2|T] || T <- [[1]]] ].

= [ [1|[2]],
[2|[1]] ].

= [ [1,2], [2,1] ].
perms([1,2,3]) = [ [[1|T] || T <- perms([2,3])],
[[2|T] || T <- perms([1,3])],
[[3|T] || T <- perms([1,2])] ].

= [ [[1|T] || T <- [[2,3], [3,2]]],
[[2|T] || T <- [[1,3], [3,1]]],
[[3|T] || T <- [[1,2], [2,1]]] ].

= [ [1|[2,3]], [1|[3,2]],
[2|[1,3]], [2|[3,1]],
[3|[1,2]], [3|[2,1]] ].

= [ [1,2,3], [1,3,2],
[2,1,3], [2,3,1],
[3,1,2], [3,2,1] ].

Erlang Function Call Precedence

My goal is to lazy evaluate results. I want to get the nth element after performing some operations on a list of elements and I don't want to actually perform the computation unless it is required. I also want to show how to call the returned value which is a function immediately.

Generate a list with sequence 1 to 5.
1> lists:seq(1, 5).
An anonymous function that returns the double. This as such does nothing.
2> fun(X) -> 2*X end. 
An anonymous function which returns a function which when called returns the double.
3> fun(X) -> (fun() -> 2*X end) end.
We can also write this without brackets
4> fun(X) -> fun() -> 2*X end end.
Call the above function for each element in the list. We will use map for that. Let's assign the resultant list to a variable L.
5> L = lists:map(fun(X) -> (fun() -> 2*X end) end, lists:seq(1, 5)).
We know the function returns another function and results are not evaluated until we call the returned function.
Say, instead of doubling operation, we perform sightly heavier computations. Here we are not performing the computation. We intend to perform the operation only when the result is required.

Now let's get, say the 3rd element from the above list.
6> lists:nth(3, L).
But I want to get the computed result. So I have to call the returned function. Now this is where it get slightly tricky. We can call the returned function by assigning it to a variable and calling it or call it directly.
7> F = lists:nth(3, L).
8> F().
To call the returned function directly, we have to wrap the whole expression in parenthesis and then call.
9> (lists:nth(3, L))().
We cannot call it like lists:nth(3, L)() which will produce an error 1: syntax error before: '(. It is due to the precedence rules in the Erlang grammar.

Here we are able to call it without parenthesis.
10> fun(X) -> 2*X end (3).
In this case, it works with parenthesis as well.
11> (fun(X) -> 2*X end)(2).

Saturday, October 26, 2013

Erlang for Maemo

Erlang for Nokia N900 is available from the maemo extras-devel repository.
apt-get install erlang
PS: Check if rootfs has enough space before the installation.
df -h /
df -h

Thursday, October 10, 2013

Forward Requests From Grails Spring Security Filter

I was trying to get a request to be send to a specific controller action in case of session expiry. I was trying to use redirect and later forward (to avoid additional requests from the client) method from grails. But I keep getting this error even though the params to the methods are all correct.
Message: No signature of method: com.rwi.springsecurity.filters.CustomSessionExpiryFilter.forward() is applicable
for argument types: (java.util.LinkedHashMap) values: [[controller:exampleApi, action:init, params:[...]]]
Then it struck, maybe by default we cannot use those grails methods in the spring security classes as they are under src/groovy and also the doc mentions that the method is to forward from one action to another. So in this case, to forward a request we can use methods from the servlet classes.

Forward a request to a controller action, where api is the controller and init is the action which includes query string as well.
request.getRequestDispatcher("/api/init").forward(request, response)
For a redirect request we can use response.sendRedirect() method with uri containing the necessary params like query strings appended manually. An example code snippet follows.
// Construct the redirect uri
String responseUri = {
String uri = request.forwardURI
String qs = request.getQueryString()
return (qs?.size() > 0) ? "${uri}?${qs}" : uri

Monday, October 7, 2013

Groovy's JsonBuilder Nuances

JsonBuilder can be used to construct JSON objects, serialize as JSON string etc. A call() method is executed depending on the type of parameter used, and the results vary accordingly, which can be better demonstrated using examples.
import groovy.json.JsonBuilder

long userId = 12
def json = new JsonBuilder()
def result = json { //args as block
userId userId
json.toString() // produces error
groovy.lang.MissingMethodException: No signature of method: is applicable for argument types: (java.lang.Integer) values: [12] Possible solutions: wait(), any(), abs(), wait(long), wait(long, int), and(java.lang.Number)

The above example does not work even if the key is given as a string. Using a map as the argument to the call() method of the JsonBuilder class gives us the correct result. As we can see the above method uses a block, which can be used if the name of keys are different from any variable names in the scope.
long userId = 12
long abc = 123
long z = 987
def json = new JsonBuilder()
json userId: userId, //args as map
abc: abc,
z: z
json.toString() //{"userId":12,"abc",123,"z": 987}
It is better to use as a map instead of a block (closure), which gives the intended result in most of the cases.

In JavaScript it is pretty straight forward.
var a = 1
JSON.stringify({a: a}) //"{"a": 1}"
Below are examples where key contains the value in the variable.
json "${userId}": userId, z: z
json.toString() //{"12":12,"z",987}
var a = 1, j = {}
j[a] = a
JSON.stringify(a) //"{"1":1}"

Friday, October 4, 2013

Groovy: Get First n Elements from a List

A Groovy snippet to get first n elements from a list.
def a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a.take(3) // [1, 2, 3]

Thursday, October 3, 2013

Getting Started With GroovyFX

To run GroovyFX programs we need to have groovyfx.jar and jfxrt.jar added to the classpath. The JDK I am using is v1.8.0-ea. JavaFX SDK is bundled with JDK from Java 7u4 and above.

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Intro.groovy: 3: unable to resolve class groovyx.javafx.GroovyFX
@ line 3, column 1.
import groovyx.javafx.GroovyFX

1 error
The above error is thrown if groovyfx.jar is not found. The easiest way to fix this would be to use Grapes and annotate the source with @Grab('org.codehaus.groovyfx:groovyfx:0.3.1'), which will download and add the groovyfx-0.3.1.jar in the .groovy directory. Another way would be to download it from maven repository and add it to classpath manually (or use mvn).
To add it manually, create a environment variable with name CLASSPATH with value .;F:\javaLibs\groovyfx-0.3.1.jar; (update the path F:\javaLibs to reflect your directory preferences). In Windows the delimiter is ; where as under GNU/Linux it is :. This example uses Windows. There is a dot at the beginning so that the current working directory is also included. If the variable already exists, just append it to the end preceeding the appropriate delimiter.

Caught: java.lang.NoClassDefFoundError: javafx/application/Application
java.lang.NoClassDefFoundError: javafx/application/Application
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
The above error is caused because Groovy could not find the jfxrt.jar file in the classpath. To resolve this append %JAVA_HOME%\jre\lib\jfxrt.jar; to the classpath variable.

The value of the CLASSPATH should look like
These are the two main errors that gets between running GroovyFX programs. Let us run a sample program from the website.
// Hello.groovy
import groovyx.javafx.GroovyFX

GroovyFX.start {
stage(title: "GroovyFX Hello World", visible: true) {
scene(fill: BLACK, width: 500, height: 250) {
hbox(padding: 60) {
text(text: "Groovy", font: "80pt sanserif") {
fill linearGradient(endX: 0, stops: [PALEGREEN, SEAGREEN])
text(text: "FX", font: "80pt sanserif") {
fill linearGradient(endX: 0, stops: [CYAN, DODGERBLUE])
effect dropShadow(color: DODGERBLUE, radius: 25, spread: 0.25)
Run it as
groovy Hello.groovy
or compile and run as
groovyc Hello.groovy
groovy Hello
will give the output as shown below.