haskell - Scotty Convert GET Parameter / Lazy.Text 转换
问题描述
我尝试将 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
到 a Num
(or Maybe...
) 并将函数结果转换回 a 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]’
解决方案
感谢 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
,但这将不在此处讨论。
推荐阅读
- java - Java合并排序递归奇怪
- c - 如何在c中使用数组打开文件
- security - 通过命令行安全地发送密码而不暴露在 ps/wmic (Windows,Unix) 中
- javascript - 如何在javascript中访问row id并实现多行的展开/折叠?
- ios - 在ios中获取renewable in app产品购买的收据信息
- python - 尽管安装了torchvision,但无法加载它
- genetic-algorithm - 整洁:物种形成
- django - 使用基于 Django 类的 CreateView 执行多步骤表单
- css - Bootstrap 4 添加垂直分隔管
- microsoft-graph-api - 如何摆脱 Microsoft Access Data Anytime Consent?