Skip to content

Instantly share code, notes, and snippets.

@expipiplus1
Created February 21, 2019 13:39
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 expipiplus1/2a49a40dc8dd37e396a7a0e996d5842e to your computer and use it in GitHub Desktop.
Save expipiplus1/2a49a40dc8dd37e396a7a0e996d5842e to your computer and use it in GitHub Desktop.
{-# LANGUAGE LambdaCase #-}
module Main where
import Data.Traversable
import System.Environment
import Data.Foldable
data A
= N
| Add A A
| Sub A A
| Mul A A
| Div A A
| Pow A A
pretty :: Double -> A -> String
pretty n a =
let f = \case
N -> show n
Add x y -> "(" ++ f x ++ "+" ++ f y ++ ")"
Sub x y -> "(" ++ f x ++ "-" ++ f y ++ ")"
Mul x y -> "(" ++ f x ++ "*" ++ f y ++ ")"
Div x y -> "(" ++ f x ++ "/" ++ f y ++ ")"
Pow x y -> "(" ++ f x ++ "^" ++ f y ++ ")"
in f a ++ " = " ++ show (eval n a)
eval :: Double -> A -> Double
eval n = \case
N -> n
Add x y -> eval n x + eval n y
Sub x y -> eval n x - eval n y
Mul x y -> eval n x * eval n y
Div x y -> eval n x / eval n y
Pow x y -> eval n x ** eval n y
trees :: Int -> [A]
trees 1 = [N]
trees n =
[ op l r
| s <- [0 .. pred n]
, l <- trees s
, r <- trees (n - s)
, op <- [Add, Sub, Mul, Div, Pow]
]
main = do
[n] <- fmap read <$> getArgs
let t = 6
traverse_ (putStrLn . pretty n) . filter (((==) t) . eval n) $ trees 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment