haskell - GHC compiler not complaining about incorrect code paths -


i'm approaching haskell view of converting runtime errors compile-time errors. expect compiler figure out code paths in following code not error free. if authorizeuser returns unauthorizedcommand call (command $ authorizeuser cmd userid) fail during runtime.

data command = unauthorizedcommand | command {command :: string, userid :: string}  authorizedusers = ["1", "2", "3"]  authorizeuser :: string -> string -> command authorizeuser cmd userid = if (userid `elem` authorizedusers) command {command=cmd, userid=userid} else unauthorizedcommand  main :: io () main =   cmd <- getline   userid <- getline   case (command $ authorizeuser cmd userid) of     "ls" -> putstrln "works"     _ -> putstrln "not authorized" 

is there compiler switch enable such checking?

the main problem in example using record syntax in data type multiple constructors can end record selector functions partial. it's therefore not recommended ever mix records , multiple constructors unless constructors have identical record fields.

the simplest solution not use record syntax here , define own command accessor makes error case explicit maybe return type:

data command = unauthorizedcommand | command string string  command :: command -> maybe string command unauthorizedcommand = nothing command (command cmd _)     = cmd 

a more complex way check during compile time use gadts encode permission level in types.

{-# language gadts #-} {-# language datakinds #-}  data permission   = authorized | unauthorized  data command p   unauthorizedcommand :: command unauthorized   command :: {command :: string, userid :: string} -> command authorized 

now type of command selector command authorized -> string compile time error if try use unauthorized command.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -