Created
January 4, 2012 14:08
-
-
Save timjb/1560200 to your computer and use it in GitHub Desktop.
Trying to understand C declarations
This file contains hidden or 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.Maybe (maybe) | |
| import Data.List (intercalate) | |
| data CType = CInt | |
| | CDouble | |
| | CChar | |
| | CVoid | |
| | CPointer CType | |
| | CArray CType (Maybe Int) | |
| | CFun CType [CType] | |
| deriving (Read) | |
| toC :: CType -> String -> String | |
| toC CInt a = "int " ++ a | |
| toC CDouble a = "double " ++ a | |
| toC CChar a = "char " ++ a | |
| toC CVoid a = "void " ++ a | |
| toC (CArray t n) a = toC t (a ++ '[':(maybe "" show n) ++ "]") | |
| toC (CPointer t) a = toC t ("(*" ++ a ++ ")") | |
| toC (CFun t ts) a = toC t (a ++ '(':(intercalate ", " $ map (flip toC "") ts) ++ ")") | |
| main :: IO () | |
| main = do | |
| -- Test: Examples from chapter 5.12 of "The C Programming Language" | |
| putStrLn $ toC (CPointer CChar) "argv" | |
| putStrLn $ toC (CPointer (CArray CInt (Just 13))) "daytab" | |
| putStrLn $ toC (CArray (CPointer CInt) (Just 13)) "daytab" | |
| putStrLn $ toC (CPointer (CFun CVoid [])) "comp" | |
| putStrLn $ toC (CFun (CPointer (CArray (CPointer (CFun CChar [])) Nothing)) []) "x" | |
| putStrLn $ toC (CArray (CPointer (CFun (CPointer (CArray CChar (Just 5))) [])) (Just 3)) "x" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment