Monday, 21 October 2013

Rosetta Code

I went over to the Rosetta Code website to look at the examples of Julia in action. Amongst them I found one marked as not completed so I took the challenge. This code picks the middle three digits from numbers returning an error message if it's not possible. It illustrates the use of the @sprintf macro for formatting text. You don't waste a lot of keystrokes when you write Julia:

function middle(i)
let s = string(abs(i)) , l = length(s) , mid = int((l+1)/2)
l < 3 ?
"error: not enough digits" :
iseven(l) ?
"error: number of digits is even" :
join((s[mid-1],s[mid],s[mid+1]))
end
end
for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
println (@sprintf("%10d : ",n), middle(n))
end
view raw gistfile1.jl hosted with ❤ by GitHub

2 comments:

  1. why do you need the 'let' scope block here, I don't see the need...

    ReplyDelete
  2. I don't see it as necessary - it was in earlier code and I liked the form. There were two earlier examples of code which had been flagged as not meeting Rosetta's spec. I left them there but I see that they've been removed along with the non-compliance banner. To me it seems a nice way of introducing s,l and mid without a significant penalty. If there is a downside I'm keen to be educated though.

    ReplyDelete