Showing posts with label Racket. Show all posts
Showing posts with label Racket. Show all posts

Thursday, November 13, 2014

Practicing with sets in Advanced Student Language

This is the version I did some time ago using the Advanced Student Language of the sets exercise from the Coursera Scala course:


It helped me to practice with lambdas and to blur the border between data and functions.

Detecting balanced Parentheses in Advanced Student Language

Today I revisited this exercise from the Coursera Scala course that I did some time ago using the Advanced Student Language:

I refactored it to define the helper function f inside balanced-parentheses?.

Since it is not allowed to have nested function definitions in Advanced Student Language (it's in Racket), I defined the function using letrec and a lambda.

I had forgotten how many parentheses a cond needs in Advanced Student Language. In that sense Clojure is far more convenient.

Friday, August 15, 2014

Pascal's triangle

Here is another exercise from David Evans book Introduction to Computing, Explorations in Language, Logic, and Machines.

This is a possible solution for the Pascal's triangle exploration at the end of chapter 5:


It's a nice exercise to practise recursion.

Practising recursion with accumulate, filter and map for deeply nested lists

I'm practising recursion going through some of the exercises in David Evans book Introduction to Computing, Explorations in Language, Logic, and Machines.

These are the solutions to three of those exercises:

  1. An accumulate (reduce) function for a list which can contain arbitrarily deeply nested lists.

  2. A map function for a list which can contain arbitrarily deeply nested lists.

  3. A filter function for a list which can contain arbitrarily deeply nested lists.

You can find these and other exercises and examples from the book in this GitHub repository.

I'm loving the book.

Sunday, August 10, 2014

Some home-made implementations of map

This post originated in a conversation we had during the last Barcelona Software Craftsmanship event.

We talked about a technique to recursively processing list elements once at a time in which you have to focus on two things:
  1. How to process an empty list (the base case of the recursion)
  2. How to process a non empty list in terms of the result of processing the tail of the list (the list except the first element)
To illustrate it, let's see a possible implementation of map in SML:


It uses the following list functions:
  • hd to extract the head of the list (its first element)
  • tl to extract the tail of the list (the list except the first element)
  • null that returns true if the list is empty and false otherwise
The :: operator adds an element at the beginning of a list.

We can use a similar approach to write map in Racket:


Here the name of the functions are a bit more expressive: first, rest and empty?.
The cons function adds an element at the beginning of a list.

A more idiomatic way to write map in SML would be using pattern matching:


This version is using the same approach but pattern matching makes the code more concise and expressive.

As a bonus here is a beautiful way to append two lists in SML using the same technique and pattern matching:


This is very well explained in the first unit of of the Programming Languages course from Washington University at Coursera that I completed last year.

There is going to be a new edition starting up Oct 2. I cannot recommend it highly enough.

Thursday, July 10, 2014

Exercism: "Grains in Clojure"

This is my solution to the Grains problem in Clojure.


This solution is probably not idiomatic at all. I just wanted to use a stream like in my previous Racket solution to see how different would that be in Clojure.

This was the Racket version:


As you see they are quite different.

letfn is somehow equivalent to Racket's letrec.

My biggest problem was with cons because they behave different.

Whereas in Racket you can do:
> (cons 1 2)
'(1 . 2)
in Clojure an exception is raised when you try the same:
user=> (cons 1 2)
IllegalArgumentException 
Don't know how to create ISeq from: 
java.lang.Long  clojure.lang.RT.seqFrom (RT.java:505)
You need to write this instead:
user=> (cons 1 (cons 2 nil))
(1 2)
So in the end I used seq:
user=> (seq [1 2])
(1 2)

Another difference is that you have an integer overflow in Clojure unless you use BigInt, whereas in Racket number can be arbitrarily large.

Well, now that I've tried this. I'll try writing a more idiomatic version.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Grains problem in Racket using a home-made stream

I did the Grains problem in Racket using a home-made stream:


The stream is the function grains which returns a pair containing the first value and the generator of the rest of the stream.

The stream-for-n-steps helper gets n values from the stream.

Probably there is a function to do this directly in Racket but I wanted to remember what we did in the Coursera Programming Languages course.

Now I want to do something similar in Clojure.

Saturday, July 5, 2014

Exercism: "Extract-Transform-Load in Clojure"

This is my solution to the Extract-Transform-Load problem in Clojure.

I wrote several working versions in the REPL but this is the one that I finally submitted to Exercism as my first iteration:


I used destructuring to extract the letters and score from the key-value pair which reduce was passing to the anonymous helper.

It works but it's not very readable.

In the second iteration I introduced a helper function, assoc-pairs, to improve its readability but the naming was still bad:


So I renamed some parameters and helper functions for the third iteration:


I find that, even though, using the let form to create the local bindings that gave names to the internal helper functions, associate-score-to-letters and associate-score-to-letter helps to reveal the intention of each helper function, it also creates a "parentheses vortex" that can obscure the code at the same time.

I wish Clojure would let me define these local functions just nesting the function definitions inside the enclosing function, like the functions sqrt_iter, good_enough? and improve defined inside custom_sqrt in this Scheme example (I coded it using DrRacket):


I think that a feature like that would help to make my Clojure solution easier to read.

You can nitpick my solution here or see all the exercises I've done so far in this repository.

Sunday, June 8, 2014

Kata: FizzBuzz in Clojure with Midje

I did the FizzBuzz kata in Clojure using Midje.
You can find the resulting code in GitHub.

I love Midje's readability. Look at the tests:


This is the FizzBuzz code in Clojure:


Compare it to this version I did in Racket's Advanced Student Language some time ago:


They are more or less the same (except that Clojure's version returns a string whereas Racket's one returns a list of strings).

On one hand, I prefer Clojure's cond which is more readable because it's more lenient with the parentheses.

On the other hand, I really like how Racket's local allows to define local functions inside another function in the same way they are defined in a module.
In Clojure I also defined a local function is-multiple-of? using let but the result is less readable than using Racket's local.

Update: I keep on working on this kata on the next post, Practising Clojure sequences using FizzBuzz and REPL Driven Development.

Friday, January 31, 2014

Strategy pattern and higher-order functions?

As a practice, I'm implementing different design patterns in different languages.

I'm using the examples in the great Head First Design Patterns book as the basis for this implementations.
The book examples are written in Java, so I'll use other languages.

I've started with the Strategy pattern.
"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
The first implementation is written in C++:
I modified the book example to make it shorter. In this case the Duck class has only one configurable behavior: quacking.

This behavior is injected through its constructor but can also be modified afterwards using a setter: changeHowToQuack.

Since C++ is statically typed like Java, we need to create a base type for all the different behaviors or strategies. In this case the QuackBehavior abstract class (this would work as a Java interface).

The Duck class has a field, howToQuack, which is a pointer to an object that implements the QuackBehavior interface. When Duck's quack() method is called, it delegates the quacking responsibility to its howToQuack collaborator.

This is one of the implementations of QuackBehavior:

You can find the rest of them in this Bitbucket repository: StrategyPatternExampleCpp.
This is an example of how this code can be used:

And this would be its result:
Quack!
Squeak!
<< Silence >>
Using this pattern we've encapsulated the quacking behavior and made it possible to change how the duck quacks without changing its code just by injecting new variants of the behavior. The code respects the Open-Closed Principle for the quack behavior because it's Open to extension (by creating new types of QuackBehavior) and Closed to variation (we don't need to change the Duck class).

This way of implementing the Strategy pattern in C++ or Java has to do with two facts:
  1. They are both statically typed languages. 
  2. Functions are not first-class citizens in any of them.
In languages like Ruby or Python we wouldn't need to use an interface like QuackBehavior. We'd just need to make the different behaviors (Quack, Squeak and MuteQuack) have a common interface: quack().

Moreover, since functions are first-class citizens in these languages, we wouldn't even need classes for the different types of behaviors. In this case, functions would suffice, as you can see in this other example of the Strategy pattern in Ruby (much less verbose than the C++ or Java ones):

The Strategy pattern relies on composition. I can't avoid thinking that it's a way to compose behavior that is very similar to what you do when you're using higher-order functions in functional programming.

This last example in Racket has the same functionality as the previous two:

Even though there are no objects here, you can notice some similarities.
It's also applying the Open/Closed principle because it's injecting a behavior as a function parameter, how-to-quack, that has several variations inside a higher-order function, quack, in order to change the function behavior without having to change its code. To get a new behavior, you just need to create a new type of quack function (a different quack behavior) and pass it to quack as a parameter.

Well I hope this makes you see the Strategy pattern from a little bit different perspective.

---------------------
PS: If you're interested in JavaScript, check this implementation of the Strategy pattern by Tomás Corral.

---------------------

Update:
A functional JavaScript version (very similar to Racket's one):

Thursday, December 26, 2013

MOOCs: Programming Languages in Coursera

Two weeks ago I finished this great Coursera course by Dan Grossman from the University of Washington:

In this course we learned many of the basic concepts behind programming languages, with a strong emphasis on the techniques and benefits of functional programming.
We used three programming languages, ML, Racket, and Ruby, in order to learn learn key issues in designing and using programming languages, such as modularity and the complementary benefits of static and dynamic typing.

Dan did a great work on the videos to explain very clearly some hard concepts such as pattern matching, thunks, promises, streams, currying or partial applications. The challenging set of weekly assignments helped me a lot to digest the materials.

This course was at the same time a challenge and a great experience. As one of the course mates said on the forum:
"This course opens your mind... It's exciting! (And annoying sometimes haha)".
I can't agree more. This course was tough and challenging. Some weeks I even thought I wouldn't be able to finish the assignment. You had only two submissions per assignment and only one timed opportunity per exam. It's been probably the toughest course I've taken so far in Coursera, but at the same time it's also been the most rewarding one.

I'm very proud and happy to have been able to complete it and I've learned a lot about functional programming and a bit about object oriented programming. I think it's made me a better programmer.

To finish, I'd like to thank Dan, his team and Coursera for making this great course possible.

Friday, December 13, 2013

MOOCs: Introduction to Systematic Program Design - Part 1 in Coursera

Last month I finished this great Coursera course by Professor Gregor Kiczales from the The University of British Columbia:
This course is a 10 week introduction that presents a design method that enables you to approach the design of complex programs systematically. I saw a previous version of the course and felt curiousity about it.
Their method shows how to model the information in a problem domain, how to structure program data to mirror that information and how to further structure the data to lead to a well organized program. It also teaches how to distinguish those parts of a program that are naturally data driven, from those that should use an alternative algorithmic approach. The method also uses a first test approach to unit-testing.

The course goes slowly and Professor Kiczales explains all concepts very well. Moreover, their design methodology with its design recipes and templates helps to make explicit many of the unconscious design decisions experienced programers often do. For that reason I think it's a great introduction to programming.
In my case, having some previous programming experience, I found that applying the method systematically for most of the small programs done during the course was a bit overkilling. However, in the end, it paid off when we started working with generative recursion to produce fractals and with bactracking searches. Following the recipes of their method proved to be really useful.

Another reason to do this course was the languages it uses: several teaching languages that are subsets of Racket (a Lispy language). This makes this course a gentle introduction to the basics of functional programming.
It gave me the chance to practice a lot with recursion, immutability and higher order functions, and it also helped me to get into the "Lisp cycles":
It was a great course. I think that Professor Kiczales and his team did a really great work and I'd like to thank them and Coursera for giving us this opportunity.

I'm looking forward to start the second part.