The First Two Programs
September 7, 2012
The hello program is simple:
(define (hello)
(display "Hello, world!")
(newline))
The temperature conversion table isn’t much harder. We follow K&R by using a do
-loop and calculating the celsius temperature in-line instead of in a separate function:
(define (temp-table)
(do ((f 0 (+ f 20))) ((< 300 f))
(display f)
(display #\tab)
(display (inexact->exact (round (* (- f 32) 5/9))))
(newline)))
And here they are, the first two programs:
> (hello)
Hello, world!
> (temp-table)
0 -18
20 -7
40 4
60 16
80 27
100 38
120 49
140 60
160 71
180 82
200 93
220 104
240 116
260 127
280 138
300 149
You can run the programs at http://programmingpraxis.codepad.org/iMaXelW1.
FORTH version. It’s actually a bit tricky to get the rounding correct when using integer math…
http://pastebin.com/0g8XeqxS
bulky version :)
Rather straightforward in Python.
This produces:
>>> hello()
Hello, world!
>>> temp_table()
0 -18
20 -7
40 4
60 16
80 27
100 38
120 49
140 60
160 71
180 82
200 93
220 104
240 116
260 127
280 138
300 149
Hello world is so dull I decided to do it three ways. It’s still dull.
The normal Haskell way:
main = putStrLn "Hello World"
The silly Haskell way:
main = mapM_ putChar "Hello, World\n"
The sillier Haskell way:
main = foldM (const putChar) () "Hello World\n"
The temperature one isn’t horrible:
main = mapM_ putStrLn [show f ++ "\t" ++ show c | counter <- [0..15], let f = counter*20, let c = round $ 5/9 * (fromIntegral $ f-32)]
Och, I forgot about a nice bit of Haskell syntax that really comes in handy here, making the table slightly shorter and substantially clearer.
main=mapM_ putStrLn [show f ++ "\t" ++ show c | f<-[0,20..300], let c = round $ 5/9 * (fromIntegral $ f-32)]
Silly me…. I can make it even slightly clearer:
main=mapM_ putStrLn [show f ++ "\t" ++ show c | f<-[0,20..300], let c = round $ 5/9 * fromIntegral (f-32)]
“me” gave a bulky version in Racket. Here’s a non-bulky one:
(do ((f 0 (+ f 20)))
((> f 300))
(display f)
(write-char #\tab)
(display (round (* (/ 5 9) (- f 32))))
(newline))
[…] doing, right? This time we have another two problems from Programming Praxis, aptly title “The First Two Problems“. The whole thing is based on the idea from Brian Kernighan and Dennis Ritchie that the first […]
I made a version for R7RS scheme: https://gist.github.com/3675478
I think I may have overdone it. The problem was easy enough, so I decided to make it a bit harder by drawing the characters to the screen using turtle graphics rather than just printing them. The lion’s share of the time was spent actually making the font, but I think it turned out relatively well.
Here’s the post: The First Two Problems @ jverkamp.com
Reblogged this on Garima Goswami.
(displayln “Hello, world!”)
;; An even-less-bulky Racket temperature converter
(for ([f (in-range 0 301 20)])
(printf “~a\t~a\n” f (round (* 5/9 (- f 32)))))
A Clojure solution: