Created
October 26, 2012 23:28
-
-
Save jbpotonnier/3962166 to your computer and use it in GitHub Desktop.
Solving http://www.rubyquiz.com/quiz60.html with the power of list monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad (guard) | |
double :: Int -> Int | |
double = (2 *) | |
add_two :: Int -> Int | |
add_two = (2 +) | |
halve :: Int -> Int | |
halve n = n `div` 2 | |
paths :: Int -> Int -> [[Int]] | |
paths start target = map reverse $ search [start] | |
where | |
search :: [Int] -> [[Int]] | |
search path@(x:xs) = do | |
guard $ length path < 10 | |
op <- if even x then [double, add_two, halve] else [double, add_two] | |
let new = op x | |
guard $ new `notElem` path | |
if new == target | |
then return $ new:path | |
else search $ new:path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example :