haskell - LiftIO、do block 和语法

标签 haskell haskell-stack

我正在学习使用 Scotty 在 Haskell 中编写 API。我的文件在下面提供。我的问题是:

  1. 在路由定义中,我在 do block 中从 liftIO whatsTheTime 中提取。这有效,但看起来很冗长。有更好的语法吗?

  2. 在 whatsTheTime 定义中,我需要执行 fromString。我原以为 OverloadedString 会解决这个问题,但事实并非如此。如果有人指出为什么没有 fromString 就无法工作,我将不胜感激。

  3. 在堆栈项目中,如果我需要像 OverloadedStrings 这样的指令,我是否需要将它包含在每个需要它的文件中,还是仅包含在主入口点的顶部?

API.hs:

{-# LANGUAGE OverloadedStrings #-}

module Api
    ( whatsTheTime
    ) where

import Data.Time (getCurrentTime)
import Web.Scotty
import Data.String

whatsTheTime :: IO (ActionM ())
whatsTheTime = do
    time <- getCurrentTime
    return $ text $ fromString ("The time is now " ++ show time)

主要.hs:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Main where

import Api
import Web.Scotty
import Control.Monad.IO.Class

routes = do 
    get "/" $ do 
        res <- liftIO whatsTheTime
        res

main :: IO ()
main = do
    putStrLn "Starting server..."
    scotty 3000 routes

最佳答案

(1) 这个:

do
  res <- liftIO whatsTheTime
  res

对此进行脱糖:

liftIO whatsTheTime >>= \ res -> res

如果您查看 \m -> m >>= id 的类型:

(Monad m) => m (m a) -> m a

这正是 join 的类型 (Hoogle),因此您可以使用:

get "/" $ join $ liftIO whatsTheTime

join 是“执行返回一个 Action 的这个 Action ,并且还执行返回的 Action ”的常见习语。

(2) OverloadedStrings 用于重载字符串文字。您有一个重载的文字 "The time is now ",但您通过将其用作 (++)< 的操作数来将其限制为 String 类型String(show time 的结果)。您可以将 show time 的结果打包为 Text,而不是使用 fromStringData.Text.pack:

import Data.Monoid ((<>))
import qualified Data.Text as Text

-- ...

return $ text $ "The time is now " <> Text.pack (show time)

(3) LANGUAGE pragmas 按文件操作;正如@mgsloan 指出的那样,您可以将 OverloadedStrings 添加到 .cabal 文件中的库或可执行文件的 default-extensions: 字段。

关于haskell - LiftIO、do block 和语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47070279/

相关文章:

Haskell-Stack:构建期间出现访问冲突错误

haskell - 软件包安装后如何添加文档?

haskell - 检查堆栈目标/组件依赖于哪些目标/组件?

Haskell 工具堆栈和可执行文件大小

haskell - Parallel Haskell - GHC GC'ing sparks

class - 无法使 String 成为 Haskell 中的类的实例

haskell - Haskell 中的安全和多态枚举

haskell - GHC 优化

haskell - stack.yaml 文件是否应该检查到版本控制中?

haskell - 如何从有向无环图导出 FRP?