web developer & system programmer

coder . cl

ramblings and thoughts on programming...


project euler: problem 255

published: 14-04-2012 / updated: 14-04-2012
posted in: development, haskell, programming, tips
by Daniel Molina Wegener

Haskell is a fabulous language, there is no looping instruction like for or while, everything is stated using recursions, like any other functional language does, preventing states across the execution, as it was defined on the computational model of most functional languages, which is known as λ-Calculus. There is no state, only purely functional state-less execution paths. The Problem 255 on the Project Euler, is related to rounded squares and the Heron’s method to calculate it, so I have implemented a Haskell program with that algorithm, which is obviously a recursive algorithm.

If we see my solution, there is a function pair to solve the problem where heronOp is the main recursive function to solve the iterations, avoiding state. On Haskell, thanks to its main functional abstraction called Monad, you can implement state machines and similar tasks using the State Monad, but states are not really required to solve anything in Haskell.


module Main (main) where

import Data.Digits (digits)
import System.Environment (getArgs)

digitBase :: Int -> Int
digitBase n | odd n = round ((2 * 10) ** ((fromIntegral n - 1) / 2))
digitBase n = round ((7 * 10) ** ((fromIntegral n - 2) / 2))

heronOp :: Int -> Int -> Int -> Int
heronOp o n m | n == m = m
heronOp o n m = heronOp o m (round ((x + y) / 2))
                where x = fromIntegral m
                      y = fromIntegral o / x

main :: IO ()
main = do [x] <- getArgs
          print
            $ heronOp (read x) (read x)
            $ digitBase $ length $ digits (read x) 10

There is — among other interesting approaches — a paper where the authors are writing about writing operating systems entirely in Haskell [«A principled approach to operating system construction in Haskell»], despite it is a functional language, it has solved the stack usage problems along recursive calls using tail calls, so you do not need to worry about recursion in almost all code, you just need to make your recursive calls lazy enough to ensure a good stack usage.


No coments yet.

post a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>