Last active
January 4, 2017 01:22
-
-
Save bblum/851e6b13dea8b2cb8288fe98e9330c37 to your computer and use it in GitHub Desktop.
This file contains 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 Data.List | |
data Op = P | M | X | D deriving (Enum, Eq, Ord) | |
data Ex = Nobe Op Ex Ex | Leaf Rational deriving Ord | |
instance Show Ex where | |
show (Leaf x) = show $ floor x | |
show (Nobe o e1 e2) = "(" ++ show e1 ++ ["+-x/" !! fromEnum o] ++ show e2 ++ ")" | |
instance Eq Ex where | |
Leaf x == Leaf y = x == y | |
Nobe o x y == Nobe p z w | o == p = (x,y) == (z,w) || elem o [P,X] && (x,y) == (w,z) | |
e1 == e2 = False | |
eval (Leaf x) = Just x | |
eval (Nobe D e1 e2) | eval e2 == Just 0 = Nothing | |
eval (Nobe o e1 e2) = [(+),(-),(*),(/)] !! fromEnum o <$> eval e1 <*> eval e2 | |
allexprs [x] = [Leaf x] | |
allexprs xs = [Nobe o l r | (ls, rs) <- nub $ splitAt <$> [1..length xs-1] <*> permutations xs, | |
l <- allexprs ls, o <- [P,M,X,D], r <- allexprs rs] | |
main = do print $ nub $ filter ((== Just 17) . eval) $ allexprs [6,6,5,2] | |
print $ nub $ filter ((== Just 24) . eval) $ allexprs [8,8,3,3] | |
print $ nub $ filter ((== Just 41) . eval) $ allexprs [2,3,5,7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment