A Dozen Lines Of Code
June 3, 2016
Today’s exercise demonstrates that it is sometimes possible to do a lot with a little.
Your task is to write some interesting and useful program in no more than a dozen lines of code. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Sorting IPv4 addresses numerically, code with whitespace and shebang line minus the test data is 12 lines:
outputs:
1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
104.244.253.29
123.4.245.23
function fne(x::Union{Array{Int8,1}, BitArray{1}}) # Feature Normalized Entropy
n = length(x) # number of unique values of feature
ln = log(2, n)
z = 0.0
for c in collect(values(counter(x))); z += c*(ln – log(2, c)) / n; end
if typeof(x) <: BitArray
return z
else
me = log(2, length(unique(x))) # maximum entropy
return z / me
end
end
where counter() is a function that provides the frequencies of the elements of the (nominal) feature x.
The actual function fne() is much more comprehensive and makes use of the fe() auxiliary, that calculates the feature entropy. The normalized version of the feature entropy takes values in [0, 1] and is a much more intuitive metric for assessing a given (nominal) feature.
A Haskell program.
Definitely not a 12-line program, but a nice follow-up to the previous one. It uses the same Karplus-Strong algorithm, but mixes individual notes into a sequence of arpeggios.
Awesome applications! How does Haskell compare with C in terms of efficiency and resource management?
@Zack I’m sure there’s a lot to be said on that subject, but I’m far from the best person to say it. :-) I only play around with Haskell; I don’t use it in my day job. With that being said… Haskell has automatic memory management (i.e. garbage collection), so you may not want to use it where periodic short pauses can’t be tolerated (e.g. game programming where you want to maintain a high frame rate). Also, you have to be careful of “space leaks”, due to laziness, which is the term Haskellers use to describe memory that is unintentionally consumed by unevaluated functions and data. There are techniques and libraries for dealing with this, just as there are different ways of avoiding memory leaks, wild pointers, etc. in C/C++. In general, the freedom from having to manage your own memory is very liberating. With respect to the speed of the resulting code I’ve seen small programs equal that of C/C++. For more realistic programs I wouldn’t be surprised if Haskell was slower by a small constant factor.
For an overview of the areas in which Haskell does well (or not so well) I suggest checking out State of the Haskell ecosystem. (This is from the point-of-view of the libraries that are available. The compiler itself is solid.)