Scotty Convert GET Parameter / Lazy.Text转换

时间:2018-10-09 17:28:20

标签: haskell scotty

我尝试将GET参数传递给函数并从结果中连接字符串

{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Monoid ((<>))
import Web.Scotty

f x = x <> x
main = do
  scotty 3000 $ do
    get "/f/:x" $ do
        x <- param "x"
        text ("f(" <> x <> ") = " <> f x)

为了使我的应用程序更加有趣,我想使用一个需要参数类型为Num的实例的函数,例如

f x = x * x

如何将x转换/读取为Num(或Maybe...)并将函数结果转换回Data.Text.Internal.Lazy.Text

我尝试过

text ("f(" <> x <> ") = " <> (show $ f $ read x))

会产生错误:

• Couldn't match expected type
  ‘text-1.2.3.1:Data.Text.Internal.Lazy.Text’
  with actual type ‘[Char]’

1 个答案:

答案 0 :(得分:1)

感谢Bob Dalgleish(评论)帮助我解决了这个问题,借助pack / unpack函数,我可以解决这种情况

{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Web.Scotty

f x = x * x
main = do
  scotty 3000 $ do
    get "/f/:x" $ do
        x <- param "x"
        let res_string = show $ f $ read $ T.unpack x
        let label_string = "f(" <> (T.unpack x) <> ") = "
        text $ L.pack (label_string <> res_string)

请注意,read是“危险的”,不应用readMaybe代替,但这在这里不合主题。