# What do +, – and * with Integer do?

When using integers in C, Java or Scala, we often use what is called int.

It is presented to us as the default.

And it is extremely fast.

Ruby uses by default arbitrary length integers.

But what do +, – and * mean?

We can rebuild them, in Ruby, kind of artificially restrict the integers to what we have in other programming langauges as int:

 MODULUS = 0x100000000; LIMIT   =  0x80000000;

 def normalize(x)   r = x % MODULUS;   if (r < -LIMIT) then     return r + MODULUS;   elsif (r >= LIMIT)      return r - MODULUS;   else     return r;   end end def intPlus(x, y)   normalize(x+y); end def intMinus(x, y)   normalize(x-y); end def intTimes(x, y)   normalize(x*y); end 

x = 0x7fffffff; y = intPlus(x, x); z = intPlus(x, x); puts("x=#{x} y=#{y} z=#{z}"); 

What is the outcome?

Exactly what you get when doing 32-Bit-Ints in C, Java, Scala or C#:
 x=2147483647 y=-2 z=-2 

int is always calculated modulo a power of two, usually . That is the
x % MODULUS  in normalize(). The Rest of the function is just for normalizing the result to the range .

So we silently get this kind of result when an overflow situation occurs, without any notice.
The overflow is not trivial to discover, but it can be done.
For addition I have described how to do it.

I gave a talk that included this content adapted for Scala at Scala Exchange 2015.

# Conversion of ASCII-graphics to PNG or JPG

Images are usually some obscure binary files. Their most common formats, PNG, SVG, JPEG and GIF are well documented and supported by many software tools. Libraries and APIs exist for accessing these formats, but also a phantastic free interactive software like Gimp. The compression rate that can reasonably be achieved when using these format is awesome, especially when picking the right format and the right settings. Tons of good examples can be found how to manipulate these image formats in C, Java, Scala, F#, Ruby, Perl or any other popular language, often by using language bindings for Image Magick.

There is another approach worth exploring. You can use a tool called convert to just convert an image from PNG, JPG or GIF to XPM. The other direction is also possible. Now XPM is a text format, which basically represents the image in ASCII graphics. It is by the way also valid C-code, so it can be included directly in C programms and used from there, when an image needs to be hard coded into a program. It is not generally recommended to use this format, because it is terribly inefficient because it uses no compression at all, but as intermediate format for exploring additional ways for manipulating images it is of interest.
An interesting option is to create the XPM-file using ERB in Ruby and then converting it to PNG or JPG.

# Find the next entry in a sequence

In Facebook, Xing, Google+, Vk.com, Linkedin and other of these social media networks we are often encountered with a trivial question like this:
 1->2 2->8 3->18 4->32 5->50 6->72 7->? 
There are some easy patterns. Either it is some polynomial formula or some trick with the digits.
But the point is, that any such sequence can easily be fullfilled by a polynomial formula. That means we can put any value for 7 and make it work. Or any answer is correct. So what would probably be the real question is the most simple function to full-fill the given constraints. Simplicity can be measured in some way… If the solution is unique is unclear, but let us just look at the polynomial solution.

A function is needed that takes as parameter a list of key-value-pairs (or a hash map) and that yields a function such that the function of any of the key is the associated value.

Assuming a polynomial function in one variable we can make use of the chinese remainder theorem, which can be applied to univariate polynomials over a field as well as to integral numbers. For a polynomial p(X) we have

where is the polynomial variable and is a concrete value.

We are looking for a polynomial such that for given values we have

or in another way

which is exactly the Chinese remainder theorem.
Let

and

We can see that for all the polynomials

have the properties

or

where is the Kronecker symbol, which is 0 if the two indices differ and 1 if they are equal.
Or as congruence:

Then we can just combine this and use

This can easily be written as a Ruby function
 def fun_calc(pairs)   n = pairs.size   result = lambda do |x|     y = 0     n.times do |i|       p_i = pairs[i]       x_i = p_i[0].to_r       y_i = p_i[1].to_r       z = y_i       n.times do |j|         if (j != i)           p_j = pairs[j]           x_j = p_j[0]           z *= (x - x_j) / (x_i - x_j)         end       end       y += z     end     y   end   result end 
This takes a list of pairs as a parameter and returns the polynomial function als lambda.
It can be used like this:
 lop = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 64]]

 f = fun_calc(lop) 

20.times do |x|   y = f.call(x)   puts sprintf("%6d -> %6d", x, y) end 
Put this together into a ruby program and add some parsing for the list of pairs or change the program each time you use it and all these „difficult“ questions „that 99.9% fail to solve“ are not just easy, but actually soluble automatically.

This is interesting for more useful applications. I assume that there will always be situations where a function is needed that meets certain exact values a certain inputs and is an interpolation or extrapolation of this.

Please observe that there are other interesting and useful ways to approach this:

• Use a „best“ approximation from a set of functions, for example polynomials with a given maximum degree
• use cubic splines, which are cubic polynomials within each section between two neighboring input values such that at the input values the two adjacent functions have the same value (, of course), the same first derivative and the same second derivative.

For highway and railroad construction other curves are used, because the splines are making an assumption on what is the -axis and what is the -axis, which does not make sense for transport facilities. They are using a curve called Clothoid.

Use Java, C, Perl, Scala, F# or the programming language of your choice to do this. You only need Closures, which are available in Java 8, F#, Scala, Perl, Ruby and any decent Lisp dialect. In Java 7 they can be done with an additional interface as anonymous inner classes. And for C it has been described in this blog how to do closures.

# Testing Java- and C-programs with Ruby and Perl

It is very important to write good unit tests for software that is non-trivial and that is relied on by other pieces of software.
Often the logic of the software can easily be covered by the native testing facilities of the programming language, like JUnit for Java or, much less well known but available, CUnit for C. When a lot of framework code is involved or third party libraries are used heavily, there is almost no other way for certain tests, because setting up the environment cannot easily be achieved elsewhere.

But we also encounter cases where writing good unit tests in the same language as the library itself becomes a pain. We procrastinate the issue of writing them and end up with way too little or no unit tests at all. A lot of software deals with doing some calculations or transformations of numbers and strings, usually a lot of numbers and a lot of strings. Now Strings are the strength of the Perl programming language and are not really implemented very well or at least not very powerful or easy to use in most other languages. Specifically the String facilities of Perl are much superior to those of Java and C. Off course our software needs to perform well, it needs to integrate into the environment and follow the global corporate software standards, so Java or C or some other programming language is the choice that should not be challenged here for the productive software. But some tests of the functionality can more easily be achieved by iterating over some input data and creating output of the input data combined with the results. This can be perl code already or something really easy to parse. Perl is really the tool that can parse almost anything, but we do not really want to be distracted by unnecessary work but get our job done. So something like generating Perl code or CSV or YAML or JSON, but please not XML if not really needed, should do. Then we can pipe the output to perl or to a perl script and this will tell us, if everything is ok. When we know our platform, it can even be done that the Java- or C-Unit-test stores the output to a file or pipe and calls the Perl script on it and fails or succeeds depending on its output.

When it comes to numeric types, Ruby is very strong. It has unlimited size integers by default, which can be casted to n-bit-integers using constructions like
xx=x&(1<<n)-1,
it has Rational, LongDecimal (as an external gem) and Complex and is easily extendible.

Usually we can expect that corporate constraints on which tools and programming languages may be used are less restrictive when it comes to unit tests. Integrating this on a continuous integration platform is a job that needs to be addressed but it is worth the effort, if a lot of tests become easier with this approach. And doing tests in another language makes tests more credible.

Off course the general idea is applicable for other combinations. Look into Scala, F#, Clojure, JavaScript, Python and some others as well, if they seem to be more helpful than Ruby or Perl for your unit testing automation. But this does indeed raise the question if a world where corporate policies allowed Scala and Closure instead of Java, F# instead of C# and Elixir instead of Erlang and PL/I instead of Cobol would be better.

# Why I still like Ruby

Some years ago Ruby in conjunction with rails was an absolute hype. In the Rails User Group in Zürich we had meetups with 30 people every two weeks. The meetings every two weeks have been retained, but often we are just five to ten people now. Is the great time of Ruby over or is it just a temporary decline? Is Perl 6 now taking over, since it is ready?

Perl 6 is cool and could challenge Ruby and it is now getting more and more towards production readiness. This will happen next year. This is what we will say next year. But Perl 6 is or will be very cool, stay tuned… What about Perl 5? At least Allison Randall still likes Perl (5). But it has other areas of strength than Ruby, so I will leave my opinionated writing focused on Ruby.

But the hype is right now in the area of JavaScript.

There are approaches to use server side JavaScript, which are interesting, because JavaScript needs to be dealt with on the client anyway and then it is tempting to have the same language on both sides.

There are also approaches to move back from the server to the client and put more functionality into the client and make the server less relevant, at least the percentage of development effort of the client gets more and of the server gets less.

There are cool frameworks for the client development in JavaScript and in conjunction with HTML5 and these frameworks a lot can be achieved.

On the other hand we are exploring NoSQL-databases like MongoDB and MongoDB is using JavaScript with some extension library as query language.

The general hype is toward functional programming and voila, JavaScript is functional, it is the most functional of the languages that have been established for a long time and brought the functional paradigm to every developer and even to the more sophisticated web designer, everything under the radar and long time before we knew how cool functional programming is. On the other hand, Ruby (and by the way Perl and especially Perl6) allow programming according to the functional paradigm as well, if used appropriately. But in JavaScript it is slightly more natural.

Then we have more contenders. Java is not dying so soon and it is still strong on its web frameworks, JavaServerFaces and one million others, not so bad actually.

And the idea of rails or at least its name, has been taken over by the groovy guys to develop groovy on grails, which integrates nicely with a Java enterprise backend.

And the more functional languages like F#, Scala, Haskell, Erlang, Elixir (and some others for the guys that don’t find Haskell theoretical enough) are around and gaining or retaining some popularity. Will Scala support the Erlang-VM as alternative backend, like JavaScript and JVM are supported today (and dotnet-CLI in the past)? And Scala has a promising web framework with play, that does WebServices right, which is what is actually needed for the modern client side JavaScript frameworks, just as an example.

PHP was always the ugly baby, why did they implement a second Perl based on the subset of Perl they understood? Well, I am not advocating PHP at all, but there are some pretty decent PHP-applications that are working really well with high load, like Wikipedia.

The unequal twin of Ruby, Python, is doing pretty well as well on attempting to get a web framework called Django. I have not investigated it at all, but it seems to exist.

So, where is ruby and rails? Ruby is a beautiful language, that has done many things better than any of the languages mentioned here:

It is easy to learn.

It has a nice and complete and consequent concept for object orientation.

It allows all the functional programming, most of it pretty natural.

It has decent numerical types by default. Integer grow to arbitrary length, Rationals are included and Complex numbers are included. JavaScript does not even have integers, it just has one numerical type: double precision floating point.

And it has a useful and easily accessible web framework like rails and actually some contender as alternative web frameworks, like camping, sinatra and some others.

And the development effort and the amount of code needed for a certain functionality is still lower than in Java or C# or COBOL.

I do believe that the web applications that are mostly server based and are using just HTML or minimal JavaScript still have their place and will be discovered again as useful for many application areas.

To conclude, I think that Ruby did not make it to become the replacement for Java, that some saw in it and that was due according to the history of replacement of other mainstream languages that have moved to legacy in the past. But I do believe that it will play an important role for some years to come and beyond the current JavaScript hype. Off course it will be challenged again in the future and maybe something will replace the main stream and will make Ruby on Rails just another legacy area for web applications. But I don’t even have an idea what that will be. I don’t think JavaScript. Perl6, Scala, F# or Clojure do have technical potential to do so, but I do not see that happening in the near future. Maybe something new will come up? Or something old? Just remember, Ruby is about as old as Java.

We will see.

Read more in this discussion on Quora.

For those who are interested, I actually teach Ruby and it is possible to arrange trainings for two to five days, depending on the previous knowledge of the participants and the goals.

A Monad over X simply is a Monoid in the Category of Endofunctors of X.

• Monads are a concept in mathematics
• Algebra is an area of mathematics
• Category theory is an abstraction of algebra.
• Monads are defined in category theory
• Remember: in category theory we talk about infinity beyond cardinality of infinite sets…
• The „idea“ has been transplanted into something used in programming languages…
• Just think of stars in terms of astronomy, in terms of decoration and in terms of music or movies

• Actually Monads should be viewed as a design pattern
• That describes the level of abstraction

# Motivation

• Pure functional programmers are poor guys when it comes to state
• State is evil
• State is not possible or hard
• I/O is state, actually a segment of the outer world is manipulated
• Even if you are happy with state (poor IT theology…):
Multilevel nil problem 🙁

• Container type
• wrap(foo):
• class method
• can also be called unit
• Btw. arrogant Haskell guys call it return
• pass(&block)
• instance method
• Can also be called bind
• Optionally more operations (mjoin, empty, +,…)

class Identity
def initialize(value)
@value = value
end
end

def Identity.wrap(value)
new(value)
end

class Identity
def pass
yield @value
end
end


# Axioms

• Left-identity for pass:
Calling pass on a newly wrapped value is the same as applying the block to that value
• Right-identity for pass:
Calling pass with a block that only calls wrap on its parameter results in the same as its target object
• Nesting:
Nesting pass blocks should be equivalent to calling them in sequence.

# Does our Monad survive 1st law?

Identity.wrap(foo).pass do |value|
f(value)
end


Is equivalent to

f(foo)


That is how we defined pass.

# Does our Monad survive 2nd law?

bar.pass do |value|
Identity.wrap(value)
end


Is equivalent to

bar


That is how we defined pass.

# Does our Monad survive 3rd law?

bar.pass do |value_a|
f(value_a)
end.pass do |value_b|
g(value_b)
end


Is equivalent to

bar.pass do |value_a|
f(value_a).pass do |value_b|
g(valueb)
end
end


That is how we defined pass.

def Array.wrap(value)
[ value ]
end

class Array
def mjoin
inject([]) { |combined, arr| combined + arr }
end

def pass(&block)
map(&block).mjoin
end
end


# Does it work?

Have a look yourself…

Empty:

def Array::empty
[]
end


+:

# Other Examples

• Option (Some, None)

# Residue Class Rounding

Deutsch

If you do not know what residue classes are, just read on, it will be explained to the extent needed later on.

The concept of rounding seems familiar, but let us try to grab it a little bit more systematically.

Let us assume a set of numbers and a subset of it, whose elements can be represented in the programming or software environment we are having in mind. We want to use a metric . Usually we have three requirements for :

• Identity of indiscernibles:
• Symmetry:
• Triangular inquation:

Usually the number that we are dealing with can be considered to be within the world of real or complex numbers, we can hence assume that , often even or if we are honest . Then we are usually working with , which is kind of implicitly clear. If you do not know complex numbers, just think of real or even rational numbers, which is the most common case anyway. Off course the concepts for rounding of -adic numbers are really interesting and beautiful, but since I do not want to explain -adic numbers here, I will not extend on this issue.

What is our intuitive understanding of rounding?
Maybe just a map
,
that is chosen with certain constraints for each x in such a way that is minimal.
We need the constraints to enforce uniqueness if multiple values with minimal exist. The classical case of rounding to integral numbers has to answer the question of how to round . If is a subset of the real numbers, which is „usually“ the case, we have ordering. We can choose between the following constraints:

ROUND_UP
Z.B. and and
ROUND_DOWN
Z.B. and and
ROUND_CEILING
Z.B. and and
ROUND_FLOOR
Z.B. and and
ROUND_HALF_UP
Minimize , but if multiple optimal values exist for , pick the one furthest away from 0, for example and and and
ROUND_HALF_DOWN
Minimize , but if multiple optimal values exist for , pick the one closest to 0, for example and and and
ROUND_HALF_CEILING
Minimize , but if multiple optimal values exist for , pick the largest, for example and and and
ROUND_HALF_FLOOR
Minimize , but if multiple optimal values exist for , pick the smallest, for example and and and
ROUND_HALF_EVEN
Minimize , but if multiple optimal values exist for , pick the one with even last digit. Please observe that this constraint is useful in the classical case, but it cannot be generalized. For example: and and and and
ROUND_UNNECESSARY
This constraint does not work in the mathematical sense (or only with ugly abusive math formulas), but programmatically we can do that: We try and throw an exception if not .

Usually we are thinking in the decimal system (even though our computers prefer something else, but the computer should serve us and not vice versa..). So we pick a power of ten with , so . Now we simply define
,
which means that contains all numbers of with a maximum of digits after the decimal point. This rounding works quite well with something like LongDecimal in Ruby or BigDecimal in Scala or Java, but BigDecimal offers fewer rounding modes than LongDecimal for Ruby.

Now we look at the residue class rounding. We assume such a power of ten . Then we need an integral number and a set of numbers , we call them residues. Now we define .
That means that if we fill the number with zeros to the given number of places after the decimal point, remove the decimal point and perform a division with residue of this number by , the residue lies in . In this case ROUND_HALF_EVEN can become difficult to implement and ambiguous, so we might need to sacrifice it. But even worse, we have to deal with the case that 0 is not in and provide rules how to round 0. The candidates have self-explanatory names:

• ZERO_ROUND_TO_PLUS
• ZERO_ROUND_TO_MINUS
• ZERO_ROUND_TO_CLOSEST_PREFER_PLUS
• ZERO_ROUND_TO_CLOSEST_PREFER_MINUS
• ZERO_ROUND_UNNECESSARY

An important application of this is and . This is used in Switzerland and probably other currency regions for rounding money amounts to multiples of 5 Rappen (0.05 CHF). This has already been described in „Rounding of Money Amounts„. If we have and we have the usual non-CHF-rounding case. Maybe there are even cases for and . But the concept is more general, if you like to use it.

# Ruby 2.0 coming soon

This is a translation of Ruby 2.0 in Sicht

According to blade.nagaokaut.ac.jp Ruby 2.0 is almost finished. The new features are already known and a release 2.0.0-p0 is planned for Q1 2013.