From df7d0f93d38f229ea6cdd8e391480c3f5b085af5 Mon Sep 17 00:00:00 2001 From: Yann Herklotz Date: Sun, 28 Oct 2018 22:53:38 +0000 Subject: Random generation of trees --- src/Main.hs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/Main.hs b/src/Main.hs index e25986c..0d49a3c 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -1,9 +1,9 @@ module Main where import Data.Bits +import Test.QuickCheck hiding ((.&.), (.|.)) -newtype Input = Input { getInput :: Bool } - deriving (Show) +type Input = Bool data Gate = And | Or @@ -12,12 +12,22 @@ data Gate = And | Nor deriving (Show) -data Circuit = In Input - | Node Gate Circuit Circuit - deriving (Show) +data Circuit a = In a + | Node Gate (Circuit a) (Circuit a) + deriving (Show) -eval :: Circuit -> Bool -eval (In val) = getInput val +instance Arbitrary Gate where + arbitrary = elements [And, Or, Xor, Nand, Nor] + +instance (Arbitrary a) => Arbitrary (Circuit a) where + arbitrary = do + x <- arbitrary + frequency [(1, return (In x)), (1, arbNode)] + where + arbNode = Node <$> arbitrary <*> arbitrary <*> arbitrary + +eval :: (Bits a) => Circuit a -> a +eval (In val) = val eval (Node And c1 c2) = eval c1 .&. eval c2 eval (Node Or c1 c2) = eval c1 .|. eval c2 eval (Node Xor c1 c2) = eval c1 `xor` eval c2 @@ -25,4 +35,4 @@ eval (Node Nand c1 c2) = complement $ eval c1 .&. eval c2 eval (Node Nor c1 c2) = complement $ eval c1 .|. eval c2 main :: IO () -main = print . eval $ Node And (In . Input $ True) (In . Input $ True) +main = sample (arbitrary :: Gen (Circuit Input)) -- cgit