Skip to content

Instantly share code, notes, and snippets.

@iblech
Last active March 6, 2017 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iblech/e21b0a2f5a6e0184ba43c3b1e0e70337 to your computer and use it in GitHub Desktop.
Save iblech/e21b0a2f5a6e0184ba43c3b1e0e70337 to your computer and use it in GitHub Desktop.
module Main where
import Data.List
import Control.Monad
input = [5,6,6,2]
target = 17
main :: IO ()
main = mapM_ (print . snd) $ filter ((== target) . fst) $ concatMap arb $ permutations input
-- Given a list `xs`, `arb xs` is the list of those syntax trees which
-- have the elements of `xs` at their leaves (in the same order as in `xs`).
-- Every element of `xs` occurs exactly once in those trees.
arb :: (Show a, Fractional a) => [a] -> [(a, String)]
arb [] = []
arb [x] = [(x, show x)]
arb xs = do
(as,bs) <- groups xs
(left,left') <- arb as
(right,right') <- arb bs
(op,op') <- [((+), "+"), ((-), "-"), ((*), "*"), ((/), "/")]
return (op left right, "(" ++ left' ++ ")" ++ op' ++ "(" ++ right' ++ ")")
-- Given a list `xs`, `groups xs` is the list of all possible ways
-- of splitting `xs` into two parts: a front part and a back part.
-- Both parts are not empty.
groups :: [a] -> [([a],[a])]
groups = tail . init . liftA2 zip inits tails
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment