Servant Implementation - haskell

I would like to use servant, in particular implement a literate haskell file. I cannot figure out how to use the literate haskell file. I've been searching for documentation but nothing helpful has come up.
So far I have named the file correctly with the extension .lhs and I have executed runhaskell filename.lhs. I am receiving the following error:
servantfinaltest.lhs line 150: unlit: No definitions in file (perhaps you forgot the '>'s?)
`unlit' failed in phase `Literate pre-processor'. (Exit code: 1)
This is my .lhs file below:
# Serving an API
Enough chit-chat about type-level combinators and representing an API as a
type. Can we have a webservice already?
## A first example
Equipped with some basic knowledge about the way we represent APIs, let's now
write our first webservice.
The source for this tutorial section is a literate haskell file, so first we
need to have some language extensions and imports:
``` haskell
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module Server where
import Prelude ()
import Prelude.Compat
import Control.Monad.Except
import Control.Monad.Reader
import Data.Aeson.Compat
import Data.Aeson.Types
import Data.Attoparsec.ByteString
import Data.ByteString (ByteString)
import Data.List
import Data.Maybe
import Data.String.Conversions
import Data.Time.Calendar
import GHC.Generics
import Lucid
import Network.HTTP.Media ((//), (/:))
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
import System.Directory
import Text.Blaze
import Text.Blaze.Html.Renderer.Utf8
import qualified Data.Aeson.Parser
import qualified Text.Blaze.Html
```
**Important**: the `Servant` module comes from the **servant-server** package,
the one that lets us run webservers that implement a particular API type. It
reexports all the types from the **servant** package that let you declare API
types as well as everything you need to turn your request handlers into a
fully-fledged webserver. This means that in your applications, you can just add
**servant-server** as a dependency, import `Servant` and not worry about anything
else.
We will write a server that will serve the following API.
``` haskell
type UserAPI1 = "users" :> Get '[JSON] [User]
```
Here's what we would like to see when making a GET request to `/users`.
``` javascript
[ {"name": "Isaac Newton", "age": 372, "email": "isaac#newton.co.uk", "registration_date": "1683-03-01"}
, {"name": "Albert Einstein", "age": 136, "email": "ae#mc2.org", "registration_date": "1905-12-01"}
]
```
Now let's define our `User` data type and write some instances for it.
``` haskell
data User = User
{ name :: String
, age :: Int
, email :: String
, registration_date :: Day
} deriving (Eq, Show, Generic)
instance ToJSON User
```
Nothing funny going on here. But we now can define our list of two users.
``` haskell
users1 :: [User]
users1 =
[ User "Isaac Newton" 372 "isaac#newton.co.uk" (fromGregorian 1683 3 1)
, User "Albert Einstein" 136 "ae#mc2.org" (fromGregorian 1905 12 1)
]
```
Let's also write our API type.
``` haskell ignore
type UserAPI1 = "users" :> Get '[JSON] [User]
```
We can now take care of writing the actual webservice that will handle requests
to such an API. This one will be very simple, being reduced to just a single
endpoint. The type of the web application is determined by the API type,
through a *type family* named `Server`. (Type families are just functions that
take types as input and return types.) The `Server` type family will compute
the right type that a bunch of request handlers should have just from the
corresponding API type.
The first thing to know about the `Server` type family is that behind the
scenes it will drive the routing, letting you focus only on the business
logic. The second thing to know is that for each endpoint, your handlers will
by default run in the `Handler` monad. This is overridable very
easily, as explained near the end of this guide. Third thing, the type of the
value returned in that monad must be the same as the second argument of the
HTTP method combinator used for the corresponding endpoint. In our case, it
means we must provide a handler of type `Handler [User]`. Well,
we have a monad, let's just `return` our list:
``` haskell
server1 :: Server UserAPI1
server1 = return users1
```
That's it. Now we can turn `server` into an actual webserver using
[wai](http://hackage.haskell.org/package/wai) and
[warp](http://hackage.haskell.org/package/warp):
``` haskell
userAPI :: Proxy UserAPI1
userAPI = Proxy
-- 'serve' comes from servant and hands you a WAI Application,
-- which you can think of as an "abstract" web application,
-- not yet a webserver.
app1 :: Application
app1 = serve userAPI server1
```
The `userAPI` bit is, alas, boilerplate (we need it to guide type inference).
But that's about as much boilerplate as you get.
And we're done! Let's run our webservice on the port 8081.
``` haskell
main :: IO ()
main = run 8081 app1
```

First of all - if you have not written any haskell code - starting with servant and is I'd say quite ambitious - as it leverages several high level concepts/mechanisms provided by several language extensions like TypeFamilies and DataKinds ...
What you are writing is no literate haskell file - at least it violates the syntax as described here
I recommend either sticking to normal haskell files or reading the document I linked to first.
Here is a translation of your file into valid literate haskell:
# Serving an API
Enough chit-chat about type-level combinators and representing an API as a
type. Can we have a webservice already?
## A first example
Equipped with some basic knowledge about the way we represent APIs, let's now write our first webservice.
The source for this tutorial section is a literate haskell file, so first we need to have some language extensions and imports:
``` haskell
> {-# LANGUAGE DataKinds #-}
> {-# LANGUAGE DeriveGeneric #-}
> {-# LANGUAGE FlexibleInstances #-}
> {-# LANGUAGE GeneralizedNewtypeDeriving #-}
> {-# LANGUAGE MultiParamTypeClasses #-}
> {-# LANGUAGE OverloadedStrings #-}
> {-# LANGUAGE ScopedTypeVariables #-}
> {-# LANGUAGE TypeOperators #-}
> module Server where
> import Prelude ()
> import Prelude.Compat
> import Control.Monad.Except
> import Control.Monad.Reader
> import Data.Aeson.Compat
> import Data.Aeson.Types
> import Data.Attoparsec.ByteString
> import Data.ByteString (ByteString)
> import Data.List
> import Data.Maybe
> import Data.String.Conversions
> import Data.Time.Calendar
> import GHC.Generics
> import Lucid
> import Network.HTTP.Media ((//), (/:))
> import Network.Wai
> import Network.Wai.Handler.Warp
> import Servant
> import System.Directory
> import Text.Blaze
> import Text.Blaze.Html.Renderer.Utf8
> import qualified Data.Aeson.Parser
> import qualified Text.Blaze.Html
```
**Important**: the `Servant` module comes from the **servant-server** package, the one that lets us run webservers that implement a particular API type. It reexports all the types from the **servant** package that let you declare API types as well as everything you need to turn your request handlers into a fully-fledged webserver. This means that in your applications, you can just add **servant-server** as a dependency, import `Servant` and not worry about anything else.
We will write a server that will serve the following API.
``` haskell
> type UserAPI1 = "users" :> Get '[JSON] [User]
```
Here's what we would like to see when making a GET request to `/users`.
``` javascript
[ {"name": "Isaac Newton", "age": 372, "email": "isaac#newton.co.uk", "registration_date": "1683-03-01"}
, {"name": "Albert Einstein", "age": 136, "email": "ae#mc2.org", "registration_date": "1905-12-01"}
]
```
Now let's define our `User` data type and write some instances for it.
``` haskell
> data User = User
> { name :: String
> , age :: Int
> , email :: String
> , registration_date :: Day
> } deriving (Eq, Show, Generic)
> instance ToJSON User
```
Nothing funny going on here. But we now can define our list of two users.
``` haskell
> users1 :: [User]
> users1 =
> [ User "Isaac Newton" 372 "isaac#newton.co.uk" (fromGregorian 1683 3 1)
> , User "Albert Einstein" 136 "ae#mc2.org" (fromGregorian 1905 12 1)
> ]
```
Let's also write our API type.
``` haskell ignore
type UserAPI1 = "users" :> Get '[JSON] [User]
```
We can now take care of writing the actual webservice that will handle requests to such an API. This one will be very simple, being reduced to just a single endpoint. The type of the web application is determined by the API type, through a *type family* named `Server`. (Type families are just functions that take types as input and return types.) The `Server` type family will compute the right type that a bunch of request handlers should have just from the
corresponding API type.
The first thing to know about the `Server` type family is that behind the
scenes it will drive the routing, letting you focus only on the business
logic. The second thing to know is that for each endpoint, your handlers will by default run in the `Handler` monad. This is overridable very
easily, as explained near the end of this guide. Third thing, the type of the value returned in that monad must be the same as the second argument of the HTTP method combinator used for the corresponding endpoint. In our case, it means we must provide a handler of type `Handler [User]`. Well,
we have a monad, let's just `return` our list:
``` haskell
> server1 :: Server UserAPI1
> server1 = return users1
```
That's it. Now we can turn `server` into an actual webserver using
[wai](http://hackage.haskell.org/package/wai) and
[warp](http://hackage.haskell.org/package/warp):
``` haskell
> userAPI :: Proxy UserAPI1
> userAPI = Proxy
```
'serve' comes from servant and hands you a WAI Application,
which you can think of as an "abstract" web application,
not yet a webserver.
```haskell
> app1 :: Application
> app1 = serve userAPI server1
```
The `userAPI` bit is, alas, boilerplate (we need it to guide type inference).
But that's about as much boilerplate as you get.
And we're done! Let's run our webservice on the port 8081.
```haskell
> main :: IO ()
> main = run 8081 app1
```

Related

In Haskell, is it possible to qualify part of an imported module?

I'd like to be able to do something like: import qualified Data.Massiv.Array (qualified map).
This gives error: parse error on input `map'.
Or better yet, import qualified Data.Massiv.Array (qualified map) as AM, so I also can access foo as either foo or AM.foo, unless foo == map, then I have to use AM.map. This is to avoid conflict with Prelude.map.
Write two imports and you can use map as AM.map and use other functions without AM..
import qualified Data.Massiv.Array as AM
import Data.Massiv.Array hiding (map)

Module imports form a cycle

Hello i was wondering how do you solve circular dependency in Haskell
I have :
Module for a type.
module Company where
import Tclass
data Worker=Worker{
age::Int,
name::String,
title::Title,
income::Int
}
data Title=Manager | Dev | Tester deriving (Show)
data Company=Company{
cname::String,
people::[Worker],
yf::Int
}
Module for the instance of the typeclass
module Tclass where
import System.Environment
import Company
class Console a where
wLine::a->IO()
rLine::IO String->a
instance Show Worker where
show w="to be defined"
print =putStr . show
If i just want to load the type in ghci and use it ; how do i import them without getting the error:
Module imports form a cycle:
module `Tclass' (.\Tclass.hs)
imports `Company' (Company.hs)
which imports `Tclass' (.\Tclass.hs)
P.S I have tried creating a auxiliary module that imports the two modules and the two modules would import it too,but no luck with this one either :
module Au where
import Tclass
import Company
module Company
import Au
module Tclass
import Au
Moving the Show instance to the other module, you can break the cycle:
module Tclass where
import System.Environment
import Company
class Console a where
wLine::a->IO()
rLine::IO String->a
and
module Company where
data Worker=Worker{
age::Int,
name::String,
title::Title,
income::Int
}
instance Show Worker where
show w="to be defined"
print =putStr . show
data Title=Manager | Dev | Tester deriving (Show)
data Company=Company{
cname::String,
people::[Worker],
yf::Int
}

Haskell Reflex: type error on Strings

I'm working through the reflex-frp examples on the github page and got stuck on the Dynamics and Events section. I try to use ghcjs to compile the following code:
{-# LANGUAGE OverloadedStrings #-}
import Reflex
import Reflex.Dom
main = mainWidget $ el "div" $ do
t <- textInput def
text "Last key pressed: "
let keypressEvent = fmap show $ _textInput_keypress t
keypressDyn <- holdDyn "None" keypressEvent
dynText keypressDyn
but I get the error
eventTest.hs:11:13: error:
• Couldn't match type ‘[Char]’ with ‘Data.Text.Internal.Text’
Expected type: Dynamic
(SpiderTimeline Global) Data.Text.Internal.Text
Actual type: Dynamic (SpiderTimeline Global) String
I understand that the String should be parsed instead as Data.Text.Internal.Text, but don't know how to make this happen - I thought the OverloadedStrings statement at the top was supposed to resolve this issue. Does anybody know how to fix this error?

Haskell Diagrams Output without commandline

I have one question: I know how to output svg file with a help of ghc --make Strukturine.hs command in Terminal. As I understood it uses import Diagrams.Backend.SVG.CmdLine . Is it possible somehow load Strukturine.hs file with the help of :load Strukturine.hs in terminal and then just put the name of function for example: strukturine. That function should output a scheme/picture (to svg file).
The beginning of Strukturine.hs file looks like this
{-# LANGUAGE NoMonomorphismRestriction #-}
module Strukturine where
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Data.Maybe (fromMaybe)
import Data.Char
import Input
import qualified Input(getNumber) --other module
main = mainWith(strukturine :: Diagram B R2)
You can use the function renderSVG from Diagrams.Backend.SVG.
renderSVG :: FilePath -> SizeSpec2D -> Diagram SVG R2 -> IO ()
For example to render a 400x400 svg:
import Diagrams.Backend.SVG (renderSVG)
outputFile :: FilePath
outputFile = "strukturine.svg"
dimensions :: SizeSpec2D
dimensions = mkSizeSpec (Just 400) (Just 400)
strukturineDiagram :: Diagram SVG R2
strukturine = do renderSVG outputFile dimensions strukturineDiagram
See http://projects.haskell.org/diagrams/haddock/Diagrams-Backend-SVG.html#v:renderSVG
And for more specific rendering, see: http://projects.haskell.org/diagrams/doc/cmdline.html

Successfully imported Data Constructor not in scope?

What is going on here? I'm importing a data constructor, apparently successfully because I don't get an error, but when I try to use the constructor, I get an error saying its not in scope!
In Test.hs:
import Database.Persist (Key)
main = Key
Result:
$ ghc test.hs
[1 of 1] Compiling Main ( test.hs, test.o )
test.hs:3:8: Not in scope: data constructor `Key'
import Database.Persist (Key)
The above imports a type named Key but none of its constructors. To import the constructor Key of the type Key you need to do
import Database.Persist (Key(Key))
or just
import Database.Persist (Key(..))
to import all constructors of the given type.
In order to import a constructor you must use the following syntax
import Database.Persist (Key (..))
Generally, when importing a type or typeclass by name only the type gets imported. The constructors and member functions must be imported using the Name (..) or Name (Constructor) syntax. This is fairly convenient as it's often the case that you need to write a type signature using an imported type even if you don't ever need to construct or examine values of that type.

Resources