Sequence expressions and side-effects in F#

September 6, 2013 at 4:11 PMMichele Mottini

I discovered an interesting problem when using sequence expression to read a text. The original case was more complex, but here is a simple example to reproduce the problem – a function reading all the lines of text from a text stream, returning them as a sequence of string using a sequence expression:

let readlines (reader: System.IO.TextReader) = 
  seq {
    let line = ref (reader.ReadLine())
    while !line <> null do 
      yield !line
      line := reader.ReadLine()

Reading a two-lines text:

readlines (new System.IO.StringReader"A

produces as expected:

val it : seq<string> = seq ["A"; "B"]

Now define a simple function that checks if a sequence is empty and return either the string “Empty” or the string “XX items”:

let test s = 
  if Seq.isEmpty s then 
    sprintf "%d items" (Seq.length s)

Apply it to the same sequence as above:

readlines (new System.IO.StringReader"A
B") |> test

and the result is

val it : string = "1 items"

that is very wrong: the sequence contains 2 lines, not 1.

The problem is that the call to Seq.isEmpty reads the first line, moving the text reader to the second line (i.e. causing a side-effect) – and so causing subsequent uses of the sequence to skip the first line.

In this case the problem is with a text reader, but any call causing side-effects within a sequence expression is bound to cause the same unexpected behavior.

One possible solution is to cache the resulting sequence:

let readlines (reader: System.IO.TextReader) = 
  seq {
    let line = ref (reader.ReadLine())
    while !line <> null do 
      yield !line
      line := reader.ReadLine()
  } |> Seq.cache

that prevents double calls to read the same element in the sequence, fixing the problem.

Another solution is to create the reader within the sequence expression:

let readlinesStr str = 
  seq {
    use reader = new System.IO.StringReader(str)
    let line = ref (reader.ReadLine())
    while !line <> null do 
      yield !line
      line := reader.ReadLine()

that causes a new reader to be created each time sequence is accessed, avoiding side-effects.

Posted in: Programming

Tags: , , ,

Phrase of the week

September 1, 2013 at 12:38 PMMichele Mottini

I have distinct reservations as to how good "the good old days" were.

Franklin D. Roosevelt in a speech to the Canadian parliament.

Posted in: Opinion


Phrase of the week

August 25, 2013 at 6:51 AMMichele Mottini

I have three farms, half my father’s herd, all my mother dowry – including what she has hidden from my father.

Nikolai Gogol in ‘Taras Bulba’

Posted in: Opinion


Relativistic collision in one dimension

August 22, 2013 at 9:05 AMMichele Mottini

I want to modify my billiard simulator to use special relativity instead than classical mechanics. The idea is to add the speed of light as a parameter, so that it is possible to see the relativistic effects increase as the speed of light decreases.

I need to derive the relativistic formulas for ball-side and ball-ball collisions, as well as adjusting the collision detection to account for relativistic time dilation and length contraction. I did not find anything much ‘ready made’ in various books and papers found on the Internet, so I’ll start working out the simple cases and (hopefully) build from that.

The simplest collision is ball-ball head-on:


It can be treated as one-dimensional, ignoring the vertical coordinate. The energy-momentum conservation equations are:

$$ \frac{E}{c^2} = m_0\gamma_0 + m_1\gamma_1 = m’_0\gamma’_0 + m’_1\gamma’_1 = \frac{E’}{c^2} $$

$$ p = m_0 \gamma_0 v_0 + m_1 \gamma_1 v_1 = m’_0 \gamma’_0 v’_0 + m’_1 \gamma’_1 v’_1 = p’$$

where \(m_0\) and \(m_1\) are the rest masses of the two balls and

$$ \gamma_0 = \frac{1}{\sqrt{1 - v_0^2 / c^2}},  \gamma_1 = \frac{1}{\sqrt{1 - v_1^2 / c^2}}$$

with \(c\) the speed of light. The primed symbols indicate the same quantities after the collision.

The collision can be not perfectly elastic, and so the rest masses of the balls can change, i.e. some of the kinetic energy gets converted into internal energy of the balls – hence \(m’_0\) and \(m’_1\) instead than just \(m_0\), \(m_1\) in the right-hand sides of the conservation equations.

These equations are difficult to solve for \( v’_0 \) and \( v’_1 \). The standard way to simplify them is to switch to the rest frame of the two-balls system, i.e. the frame of reference where the total momentum is zero. Indicating with \(\bar v_0\) and \(\bar v_1\) the ball velocities in this frame of reference, the momentum conservation equation becomes:

$$ m_0 \bar\gamma_0 \bar v_0 + m_1 \bar \gamma_1 \bar v_1 = 0 = m’_0 \bar\gamma’_0 \bar v’_0 + m’_1 \bar\gamma’_1 \bar v’_1 $$

(note that the rest masses are Loretz-invariant, so they stay the same). This equation has solutions

$$ m’_0 \bar\gamma’_0 \bar v’_0 = -\epsilon m_0 \bar\gamma_0 \bar v_0 $$

$$ m’_1 \bar\gamma’_1 \bar v’_1 = -\epsilon m_1 \bar\gamma_1 \bar v_1 $$

where \(\epsilon\) is a positive constant, and the minus sign indicates that the velocities change direction after the collision. Even with this simplification, the single conservation of energy equation is not enough to determine both the rest masses and the velocities after the collision, so we need to make some further assumption.  In the classical, perfectly elastic case the energy of each ball in the zero momentum frame of reference is conserved after the collision. Assuming that this is still the case in a relativistic collision gives the equations:

$$ m_0 \bar\gamma_0 = m’_0 \bar\gamma’_0 $$

$$ m_1 \bar\gamma_1 = m’_1 \bar\gamma’_1 $$

Solving for \( \bar v’_0 \), \(m’_0\) and \( \bar v’_1 \), \(m’_1\) gives:

$$ \bar v’_0 = –\epsilon \bar v_0 $$

$$ \bar v’_1 = -\epsilon \bar v_1 $$

$$ m’_0 = m_0 \frac{\bar\gamma_0}{\bar\gamma’_0} = m_0 \sqrt\frac{1-\epsilon^2 \bar v_0^2 / c^2}{1- \bar v_0^2 / c^2} $$

$$ m’_1 = m_1 \frac{\bar\gamma_1}{\bar\gamma’_1} = m_1 \sqrt\frac{1-\epsilon^2 \bar v_1^2 / c^2}{1- \bar v_1^2 / c^2} $$

The first two equations are exactly as in the classical case, with \(\epsilon\) being the coefficient of restitution.

To compute the final velocities in the frame of reference of the billiard table it is necessary to convert the initial velocities to the zero-momentum frame of reference, apply the formulas above and then convert back the results to the original frame of reference.

The Lorentz transformation of the momentum \(p\) of a body with energy \(E\) to a frame of reference with velocity \(u\) is:

$$ p’ = \gamma_u (p – \frac{u}{c^2}E) $$

so the velocity of the zero-momentum frame of reference is

$$ \begin{equation}\tag{U} u = \frac{p}{E/c^2} = \frac{m_0\gamma_0 v_0 + m_1 \gamma_1 v_1}{m_0 \gamma_0 + m_1 \gamma_1} \end{equation}$$

and the velocity transformations are:

$$ \bar v = \frac{v-u}{1-vu / c^2} $$

$$ v’ = \frac{\bar v’+u}{1+\bar v’u / c^2} $$


$$ \begin{equation}\tag{V} v’ = \frac{u(1-u v / c^2) + \epsilon (u – v)}{1- u v / c^2+\epsilon u / c^2 (u-v)} \end{equation} $$

$$ \begin{equation}\tag{M} m’ = m \sqrt{\frac{1 – 2(1-\epsilon^2)vu/c^2 – \epsilon^2 (v^2 + u^2) / c^2 + v^2u^2/c^4}{1- (v^2+u^2)/c^2 + v^2u^2/c^4}} \end{equation} $$

Classical limit

In the classical limit (U) becomes:

$$ u = \frac{m_0 v_0 + m_1 v_1}{m_0 + m_1} $$

and (V) becomes:

$$ v’ = (1 + \epsilon) u – \epsilon v$$

combining the two:

$$ v’ = \frac {1+\epsilon} {m_0+m_1} [m_0 (v_0 – v) + m_1 (v_1 – v)] + v$$

that gives:

$$ v’_0 = –m_1 \frac {1+\epsilon} {m_0 + m_1} (v_0 – v_1) + v_0 $$

$$ v’_0 = m_0 \frac {1+\epsilon} {m_0 + m_1} (v_0 – v_1) + v_1 $$

that is the same solution as in the two dimensional classical case when \(\alpha = 0\).

Inelastic collision

For a perfectly inelastic collision \(\epsilon = 0\) and so (V) becomes simply \( v’ = u \): the two balls have always the same velocity after the collision, i.e. they ‘stick together’ as expected.

Posted in: Physics

Tags: ,

Phrase of the week

August 18, 2013 at 12:22 PMMichele Mottini

There was a great number of educated and experienced partisans who cherished the noble belief that it was of little consequence where one fought, as long as one did fight, for it was unseemly for a man of mettle not to be in battle

Nikolai Gogol in ‘Taras Bulba’

Posted in: Opinion


Phrase of the week

August 11, 2013 at 11:31 AMMichele Mottini

Over the years, peaks in sewage flow have greatly diminished, notes Rob Smith, chief sewer-flusher for Thames Water

The Economist in ‘The British at table’

Posted in: Opinion


jQuery UI widget: a slider displaying its value

August 6, 2013 at 11:47 AMMichele Mottini

For the billiard simulation user interface I wanted to select a value with a slider, displaying it at the same time – so I created a new jQuery UI custom widget based on the standard slider one. It is used to edit the coefficients of restitution and the rolling resistance coefficient here.  The Javascript source code is here, and the TypeScript definition file is here.

The widget is pretty basic: it supports only one value, the slider must be horizontal and the value is always displayed on the right of the slider.

Some problem I had writing the widget:

Case of the widget name

I originally called the widget ‘sliderWithValue’ using camel case. The name of the widget is used by default as the prefix for the complete name of the widget events – but converted to lowercase – so the name of the change event is ‘sliderwithvaluechange’ and NOT ‘sliderWithValuechange’. The documentation does not mention this conversion to lowercase.

I renamed the widget ‘valueslider’ to avoid this problem.

Setting the width of a ‘span’ element.

To space correctly the label containing the value I needed to convert a width from ems to pixels, to do this the only way I found is to create a dummy HTML element, setting its widths in ems and then getting its pixel width. The problem is that using Internet Explorer 10 this trick works fine using ‘span’ element, whereas in Chrome and Safari attempts to set the width of  this empty ‘span’ elements are ignored – it is necessary to use a ‘div’.

Events and widget ‘destroy’ method

The jQuery UI documentation instructs to wire events either directly in the widget options:

$( ".selector" ).slider({
  change: function( event, ui ) {}

or using the ‘on’ function:

$( ".selector" ).on( "slidechange", function( event, ui ) {} );

but they are not exactly equivalent: event handlers defined using ‘on’ are bot removed by the ‘destroy’ method of the widget, so if the code creates and destroys widgets dynamically it has to take care of removing the handlers defined using ‘on’.

Posted in: Programming

Tags: , , ,

Billiard simulation improvements

August 6, 2013 at 10:17 AMMichele Mottini

I just uploaded a new version of the billiard simulation with various improvements. The source code is on GitHub.


Previous versions did not properly scale the simulation, 1 pixels was equivalent to 1 meter and so the balls (and their speed) were actually gigantic. The new version correctly scales dimensions: the balls are the size of real billiard balls and the table size is standard as well.

The correct scaling produces a noticeable difference in the time required for the balls to come to a complete stop: rolling resistance causes a constant deceleration, so with the original high speeds the balls took a very long time to stop, now with realistic speeds the balls stop quite quickly.

Initial balls configuration

It is possible to choose between a list of possible initial balls configuration using a drop-down, and also to directly select the initial configuration in the URL using an ‘init=<configuration name>’  option – e.g. ‘/rpool/?init=fromLeftTwoVertical

Start/stop and velocity display

The simulation can be stopped and re-started using the ‘Start’ and ‘Stop’ buttons. When it is stopped the ‘Step’ button executes a single update step at each click.

By default the simulation starts automatically, but this can be changed adding a `stop=’ option to the URL – e.g. ‘/rpool/?init=fromLeftTwoVertical&stop=’.

When the simulation is stopped the velocity of each ball is displayed as an arrow:


Double collisions

The simulation can now optionally handle double collision as described in a previous post. To enable it use either the ‘Handle double collisions’ check-box in the page or the ‘double’ option in the URL – e.g. ‘/rpool/?init=fromLeftTwoVertical&double=


It is possible to change the value of the coefficients of restitution and of rolling resistance used in the simulation. Setting the coefficients of restitution to 1 gives perfect elastic collisions, and setting then to 0 gives perfect inelastic ones: balls ‘stick’ to each other and to the table’s side when they collide.

Posted in: Programming

Tags: ,

You can do anything you put your mind to

August 4, 2013 at 12:44 PMMichele Mottini, you can’t.

You have no control over your genes. If you are not tall, not fast and not well-coordinated you’ll never be even an half-decent basketball player (believe me – I tried that) – you can put your mind to the NBA (or even to a starting position in an amateur team) as much as you want, but ain’t going to happen.

You have no control over where and when you are born. It makes a lot of difference if you are the son of two Russian academics living in Russia or the son of two Russian academics that emigrated to the US. In the first case you can put your mind to your Internet venture idea as much as you can, but Google ain’t going to happen.

You have a maximum amount of time and energy to spend on the pursuit of your dreams. If you are gifted in math and music (lucky you!) you’ll have to choose, you won’t be able to become a math professor AND a concert pianist – regardless of how much you put your mind to both.

Chance plays a big parts in your life. There is a big difference if out of college you go to work for a company in a growing industry or in an industry that is dying – and where you end up depends on any number of irrelevant and random things. Once you are in the bad place putting your mind to improving your career would not do even nearly as good as in the good place.

Having said that, ‘You can do anything you put your mind to’ has definitely a better ring that ‘you should asses what you can realistically do given your innate abilities, birthplace and family, and then wisely invest your time and energy to achieve what you like most – or dislike the least – of the possible achievable choices’.

Posted in: Opinion


Phrase of the week

August 4, 2013 at 5:29 AMMichele Mottini

I didn't hate school; I learned things [. . .] plus I was too big to be bullied efficiently.

Iain Banks in 'The Quarry' 

Posted in: Opinion