3

我正在尝试使用 WAI 编写一个简单的斐波那契网络服务器,但我就是不知道类型。这段代码是我想做的事情的本质,但它被破坏了。该getQueryArg函数返回一个Maybe ByteString,我想在我的fibHandler函数中使用它。

  1. 如何正确处理Maybe我的fibHandler?
  2. 如何在 Maybe 上调用 putStrLn?我正在尝试fmap,但我似乎无法做到这一点。

 

{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp (run)
import Data.ByteString.Lazy.Char8 ()  -- Just for an orphan instance
import Control.Monad.IO.Class (liftIO)
import Data.Conduit
import Data.String.Utils
import Data.ByteString as BS (ByteString, putStrLn)
import Data.ByteString.Char8 as B (unpack)
import Data.Text as T (intercalate, pack, unpack)

app :: Application
app req
    | rawPathInfo req == "/fib" = fibHandler req
    | otherwise = notFoundHandler

fibHandler :: Request -> ResourceT IO Response
fibHandler req = do
    let nStr = getQueryArg (queryString req) "n"
    fmap (liftIO . BS.putStrLn) n
    let n = read nStr
    return $ responseLBS
        status200
        [("Content-Type", "text/plain")]
        (show $ fib n)

fib :: Int -> Int
fib n = foldl (*) 1 [1..n]

getQueryArg :: Query -> BS.ByteString -> Maybe BS.ByteString
getQueryArg [] key = Nothing
getQueryArg ((k,v):qs) key
    | k == key = Just v
    | otherwise = getQueryArg qs key

notFoundHandler :: ResourceT IO Response
notFoundHandler = return $ responseLBS
    status404
    [("Content-Type", "text/plain")]
    "Not found"

main :: IO ()
main = do
    BS.putStrLn $ "http://localhost:8080/"
    run 8080 $ app

[更新:此代码的工作副本在这里:https ://gist.github.com/3145317 ]

4

1 回答 1

6

与值有关的最简单的事情Maybe是使用case.

case getQueryArg foo bar of
    Nothing -> {- something went wrong, write some code to report an error -}
    Just x  -> {- everything went okay, and x is the result of the successful computation -}

一旦你这样做了几十次,你就可以毕业到速记版本:

maybe ({- went wrong -}) (\x -> {- successful x -}) (getQueryArg foo bar)
fromMaybe {- default value -} (getQueryArg foo bar)
traverse_ B.putStrLn (getQueryArg foo bar) -- this trick is a personal favorite
于 2012-07-18T23:57:24.327 回答