Skip to content

Instantly share code, notes, and snippets.

@srghma
Last active October 6, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srghma/3ce18cd61b29b017e2baefb09eabfca6 to your computer and use it in GitHub Desktop.
Save srghma/3ce18cd61b29b017e2baefb09eabfca6 to your computer and use it in GitHub Desktop.
```js
async function fetch(_ignoring) {
return {
user: {
username: "MyUsername"
}
}
}
async function fetchUserAndDoCalaculation() {
const response = await fetch('/api/users/1')
if (response.error) {
console.log('there was an error', response.error)
return undefined
}
await fetch('/api/notify-server-about-success')
const calculation = response.user.username.length()
return calculation
}
```
```js
function fetch(_ignoring) {
return Promise.resolve({
user: {
username: "MyUsername"
}
})
}
function fetchUserAndDoCalaculation() {
return fetch('/api/users/1')
.then(function (response) {
if (response.error) {
console.log('there was an error', response.error)
return undefined
}
const calculation = response.user.username.length()
return calculation
})
}
```
```hs
data IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
instance Functor IO where
fmap f x = x >>= (pure . f)
instance Applicative IO where
pure = returnIO
(<*>) = ap
-- | @since 2.01
instance Monad IO where
(>>) = thenIO
(>>=) = bindIO
return = returnIO
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) }
returnIO :: a -> IO a
returnIO x = IO (\ s -> (# s, x #))
bindIO :: IO a -> (a -> IO b) -> IO b
bindIO (IO m) k = IO (\ s -> case m s of (# new_s, a #) -> unIO (k a) new_s)
thenIO :: IO a -> IO b -> IO b
thenIO (IO m) k = IO (\ s -> case m s of (# new_s, _ #) -> unIO k new_s)
unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
unIO (IO a) = a
#####
# http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Base.html#line-1349
data User = User { username :: String } deriving (Show)
data UserFetchError = NoInternet | Timeout Int deriving (Show)
data Response = SuccessfullResponse User | ErrorResponse UserFetchError
-- show :: Show a => a -> String
-- show a = ...
-- show :: UserFetchError -> String
-- show NoInternet = "NoInternet"
-- show (Timeout a) = "Timeout" <> " " <> show a
fetch :: String -> IO Response
fetch _ignored = return myuser
where myuserResp :: Response
myuserResp = SuccessfullResponse (User { username = "MyUsername" })
fetchUserAndDoCalaculation :: IO (Maybe User)
fetchUserAndDoCalaculation = do
reponse <- fetch "/api/users/1"
case response of
SuccessfullResponse user -> do
let calculation = length (username user)
return (Just calculation)
ErrorResponse error -> do
putString (show error)
return Nothing
main :: IO ()
main = do
```
```
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
-- http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Base.html#line-966
instance Applicative Maybe where
pure = Just
Just f <*> m = fmap f m
Nothing <*> _m = Nothing
liftA2 f (Just x) (Just y) = Just (f x y)
liftA2 _ _ _ = Nothing
Just _m1 *> m2 = m2
Nothing *> _m2 = Nothing
-- | @since 2.01
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(>>) = (*>)
fail _ = Nothing
fooCalc :: Maybe Int -> Maybe Int -> Maybe Int
fooCalc ma mb = do
a <- ma
b <- mb
Just (a + b)
```
```
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
-- | @since 2.01
instance Functor [] where
fmap = map
instance Applicative [] where
pure x = [x]
fs <*> xs = [f x | f <- fs, x <- xs]
liftA2 f xs ys = [f x y | x <- xs, y <- ys]
xs *> ys = [y | _ <- xs, y <- ys]
instance Monad [] where
xs >>= f = [y | x <- xs, y <- f x]
(>>) = (*>)
fail _ = []
fooCalc :: List Int -> List Int -> List Int
fooCalc ma mb = do
a <- ma
b <- mb
[a + b]
```

content

  1. datatypes
  2. Monoid class hierarchy
  3. Monad class hierarchy
  4. IO
  5. why Monads are so popular

  1. datatypes
# http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Base.html#String
data  Bool  =  False | True
data Ordering = LT | EQ | GT

data Char = C# Char#
type  String = [Char]

data Int = I# Int#
data PeanoNumber = Zero | Suc PeanoNumber

data  ()  =  ()
data  Unit  =  Unit
data  Unit  =  MkUnit

data [] a = [] | a : [a]
data List a = Nil | Cons a (List a)

example :: [Int]
example = [1, 2, 3]
example = 1 : 2 : 3 : []

example :: List Int
example = [1, 2, 3]
example = Cons 1 (Cons 2 (Cons 3 Nil))

data Void = Void Void

data Maybe a = Nothing | Just a
data Either a b = Left a | Right b

data (a, b) = (a, b)
data (a, b, c) = (a, b, c)
data (a, b, c, d) = (a, b, c, d)
...

data Tuple a b = Tuple a b
type MyTupleWithFixedArgumentTypes = Tuple Bool Int

example :: Tuple Bool Int
example = Tuple True 1

exampleList :: [Tuple True Int]
exampleList = [Tuple True 1, Tuple False 2]

data Tree v = Leaf 
              | Node (Tree v) v (Tree v) 

treeExample :: Tree Int
treeExample = Node (Node Leaf 1 Leaf) 2 (Node Leaf 2 Leaf)



data Position = Boss | Secretary | Employee String
data User = User {
  name :: String
, postition :: Position
, password :: String
, username :: String
}

data UserValidationError = EmptyName | PasswordsDoesntMatch

mkUserWithValidation :: Json -> Either UserValidationError User
mkUserWithValidation json = ....

mkUserWithValidation :: Json -> Maybe User
mkUserWithValidation json = ....

  1. functions

  1. Monoid class hierarchy

VerifiedMonad

https://github.com/idris-lang/Idris-dev/blob/5965fb16210b18444bc0435286d4bcd4f0e260a4/libs/contrib/Interfaces/Verified.idr#L21


  1. Monad class hierarchy

  1. IO

https://www.quora.com/What-is-an-IO-Monad

data IO a = IO (State# RealWorld -> (# State# RealWorld, a #))

https://wiki.haskell.org/IO_inside

Warning: The following story about IO is incorrect in that it cannot actually explain some important aspects of IO (including interaction and concurrency). However, some people find it useful to begin developing an understanding.

The 'main' Haskell function has the type:

main :: RealWorld -> ((), RealWorld)
where 'RealWorld' is a fake type used instead of our Int. It's something like the baton passed in a relay race. When 'main' calls some IO function, it passes the "RealWorld" it received as a parameter. All IO functions have similar types involving RealWorld as a parameter and result. To be exact, "IO" is a type synonym defined in the following way:

type IO a  =  RealWorld -> (a, RealWorld)
main = do a <- ask "What is your name?"
          b <- ask "How old are you?"
          return ()

ask s = do putStr s
           readLn
Look at the next example:

main = do putStr "What is your name?"
          a <- readLn
          putStr "How old are you?"
          b <- readLn
          print (a,b)

This code is desugared into:

main = putStr "What is your name?"
       >> readLn
       >>= \a -> putStr "How old are you?"
       >> readLn
       >>= \b -> print (a,b)
main = do putStr "What is your name?"
          putStr "How old are you?"
          putStr "Nice day!"

main = (putStr "What is your name?")
       >> ( (putStr "How old are you?")
            >> (putStr "Nice day!")
          )

readLn :: Read a => IO a putStrLn :: String -> IO ()

@srghma
Copy link
Author

srghma commented Oct 5, 2019

You can embed categories in one another

@srghma
Copy link
Author

srghma commented Oct 6, 2019

composition :: (b -> c) -> (a -> b) -> a -> c
composition f g x = f (g x)

composition :: (b -> c) -> (a -> b) -> a -> c
composition f g = \x -> f (g x)

(.) :: (b -> c) -> (a -> b) -> a -> c
(f . g) x = f (g x)

(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f (g x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment