Generate a function using Template Haskell

后端 未结 2 1184
耶瑟儿~
耶瑟儿~ 2021-02-20 15:11

Is it possible to define a function using Template Haskell? For example

convertStringToValue :: String -> Int
convertStringToValue \"three\" = 3
convertStrin         


        
2条回答
  •  無奈伤痛
    2021-02-20 15:13

    Yes

    import Language.Haskell.TH
    
    generateDict :: String -> [(String, Int)] -> Q [Dec]
    generateDict fname sns = do
        let clauses = map clause sns
        return $ [FunD (mkName fname) clauses]
            where clause (s,n) =
                    Clause [LitP . IntegerL $ toInteger  n]
                           (NormalB . LitE $ StringL s )
                           []
    

    And then

    generateDict "myDict" $ zip (words "One Two Tree Four") [1..]
    
    myDict 1 -- => "One"
    

提交回复
热议问题