Wednesday, 15 July 2015

Problem of Nines, alternative method

Well, there is a quick way I find on Stack Overflow to convert an integer to the binary string equivalent - import Text.Printf and then use the printf function with "%b" as a descriptor.  If this doesn't work then you might need a newer version of Haskell.  Anyway, read this to convert to an integer and then multiply by 9 - so the list of numbers that are all made of digits 0 and 9 can be defined so:

Prelude> import Text.Printf
Prelude Text.Printf> let nines = [ 9 * read (printf "%b" n) | n <- [1..] ]

Test this:

Prelude Text.Printf> take 10 nines

So the question asked for the first of these numbers that is a multiple of 23:

Prelude Text.Printf> head [ n | n <- nines, n `mod` 23 == 0 ]

I like the other way better partly because I'm not sure how this function printf works.  Doesn't it have to take a variable number of parameters to match the placeholders in the string?  How does that work against the type checker?  Some reading to do

No comments:

Post a Comment