【问题标题】:Scotty Convert GET Parameter / Lazy.Text conversionScotty Convert GET Parameter / Lazy.Text 转换
【发布时间】:2019-03-14 13:10:53
【问题描述】:

我尝试将 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]’

【问题讨论】:

  • TextString 不一样,这已经咬了很多人,不仅在 Haskell 中。您可能需要import qualified Data.Text as T,然后使用T.pack 函数将String[Char])转换为Data.Text 格式。

标签: haskell scotty


【解决方案1】:

感谢 Bob Dalgleish (cmets) 帮助我解决这个问题,我可以通过 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 替换,但这将不在此处讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2020-02-07
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    相关资源
    最近更新 更多