How to use a Haskell pattern to check a static url using isURI at compile time? It is safe to use fromJust at run time when the URL must be valid.
For example, define staticURI like this.
{-# LANGUAGE TemplateHaskell #-} module URI where import Data.Maybe (fromJust) import Network.URI (URI, isURI, parseURI) import Language.Haskell.TH (Q, TExp) staticURI :: String -> Q (TExp URI) staticURI uri | isURI uri = [|| fromJust $ parseURI uri ||] | otherwise = fail $ "Invalid URI: " ++ uri
Then you can define your URL in other modules, for example.
{-# LANGUAGE TemplateHaskell #-} import Network.URI (URI) import URI (staticURI) url :: URI url = $$(staticURI "http://www.google.com/") badUrl :: URI badUrl = $$(staticURI "http://www.google.com/##")
When you pass the wrong url to staticURI , the compiler will throw an error.
Invalid URI: http://www.google.com/## In the Template Haskell splice $$(staticURI "http://www.google.com/##") In the expression: $$(staticURI "http://www.google.com/##") In an equation for 'url': url = $$(staticURI "http://www.google.com/##")
source share