Search code examples
haskellscotty

Scotty Convert GET Parameter / Lazy.Text conversion


I try to pass a GET parameter into a function and concat a string from the result

{-# 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)

To make my application even more interesting, I want to use a function which requires an argument type instance of Num, e.g.

f x = x * x

How can I convert/read x to a Num (or Maybe...) and convert the function result back to a Data.Text.Internal.Lazy.Text?

I tried

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

which yields errors:

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

Solution

  • Thanks Bob Dalgleish (comments) for helping me on this problem, with pack/unpack functions I could solve the situation

    {-# 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)
    

    Please note that read is "dangerous" and should not be replaced by readMaybe, but this would be off topic here.