Skip to content

Instantly share code, notes, and snippets.

@mkhan45
Created August 30, 2021 02:12
Show Gist options
  • Select an option

  • Save mkhan45/65387e306fda238bceba7e9051645ffe to your computer and use it in GitHub Desktop.

Select an option

Save mkhan45/65387e306fda238bceba7e9051645ffe to your computer and use it in GitHub Desktop.
Truth Table Generator
import Data.List (intercalate)
import Prelude hiding (or, and)
toBinArray :: Int -> [Bool]
toBinArray = reverse . helper
where helper :: Int -> [Bool]
helper 0 = [False]
helper n
| n `div` 2 == 0 = [(n `mod` 2) /= 0]
| otherwise = ((n `mod` 2) /= 0) : helper (n `div` 2)
boolTable :: Int -> [[Bool]]
boolTable n = map ((pad len) . toBinArray) [0..n - 1]
where len = ceiling ((log $ fromIntegral n) / (log 2))
pad :: Int -> [Bool] -> [Bool]
pad len ls
| (length ls) < len = pad len (False : ls)
| otherwise = ls
ttable :: ([Bool] -> Bool) -> Int -> [[Int]]
ttable f len = map (map fromEnum) boolTruthTable
where table = boolTable len
right_col = map f table
boolTruthTable = map (\(row, result) -> row ++ [result]) (zip table right_col)
or ls = foldl (||) True ls
and ls = foldl (&&) True ls
implies [False, False] = True
implies [False, True] = True
implies [True, False] = False
implies [True, True] = True
neg [p] = not p
printTable :: ([Bool] -> Bool) -> Int -> IO ()
printTable f len = putStrLn $ intercalate "\n" $ map show (ttable f len)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment