News aggregator
The Architecture of the Mighttpd High-Speed Web Server | IIJ Technology | IIJ
[Announcement] hArduino: Control your Arduino board fromHaskell
Category theory - HaskellWiki
Control.Monad provisional?
Brandon Simmons: Using GHC's RebindableSyntax for a dynamic state "Fauxnad"
I just learned about GHC's RebindableSyntax extension from chrisdoner's thread on reddit and wanted to play around with scratching a couple itches I've had. In this post I'll illustrate using RebindableSyntax to allow us to use haskell's do notation in a State-monad-like construction, in which our state type is allowed to change (I've played with this idea previously).
The dynamic state construction looks like the traditional State, but with separate types for input and output state:
{-# LANGUAGE DeriveFunctor, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} newtype DynState s1 s2 a = DynState { runState :: s1 -> (a,s2) } deriving Functor get :: DynState s s s get = DynState $ \s-> (s,s) put :: s -> DynState x s () put = DynState . const . (,) () modify :: (s1 -> s2) -> DynState s1 s2 () modify = DynState . fmap ((,) ())We can compose these by defining a (for the moment, very verbose) function dynStateBind. Interestingly, this is actually easier to understand IMHO than the State monad because the type signature makes explicit the fact that our lambda-bound state s1 is the initial state value that we run the construction on:
infixl 1 `dynStateBind` dynStateBind :: DynState s1 s2 a -> (a -> DynState s2 s3 b) -> DynState s1 s3 b dynStateBind x f = DynState $ \s1-> let ~(a,s2) = runState x s1 in runState (f a) s2We also need stand-ins for (>>) and return:
-- It would be nice if >> inherited default instances in terms of bind, as in -- an instance declaration infixl 1 `dynThen` dynThen :: DynState s1 s2 a -> DynState s2 s3 b -> DynState s1 s3 b dynThen x y = x `dynStateBind` \_ -> y dynReturn :: a -> DynState s s a dynReturn a = DynState $ \s-> (a,s)So then we can use all the nonsense above as follows:
{-# LANGUAGE RebindableSyntax #-} module Main where import Prelude -- since RebindableSyntax implies NoImplicitPrelude import DynState -- avoid lame "Not in scope: `ifThenElse'" ifThenElse b x y | b = x | otherwise = y -- oops, infinite loop fail! --ifThenElse b x y = if b then x else y test :: DynState Int Int String test = let (>>=) = dynStateBind (>>) = dynThen return = dynReturn in do i <- get -- state :: Int put (even i, show i) -- state :: (Bool, String) (b,i_str) <- get put (i+1) -- state :: Int if b then return "uh oh, even!" else return $ "pre-incremented: "++i_strIf we want to we can even enrich our bind and add some machinery to support composing traditional StateT computations with our dynamic state:
-- | a silly class to support comosing regular State monad computations with -- dynamic state computations. class Stateful n s1 s2 | n -> s1 s2 where expand :: n a -> DynState s1 s2 a instance Stateful (DynState s1 s2) s1 s2 where expand = id instance Stateful (M.StateT s Identity) s s where expand = DynState . M.runState -- category with bind sort of situation... polyDynStateBind :: (Stateful x s1 s2, Stateful y s2 s3)=> x a -> (a -> y b) -> DynState s1 s3 b polyDynStateBind x f = expand x `dynStateBind` fmap expand f -- | convert a dynamic stateful computation into the usual State monad, so we -- can compose it with normal state computations flatten :: DynState s s a -> M.State s a flatten = M.state . runState ZippersAt some point while working on zippo (you
should check out this
instead) I made up detailed notes on a DSL for zipper operations that I wished
I could shoe-horn into do or Arrow notation, but never quite could.
Lost the notes, but the idea would be to have bind expose the "focus" of the zipper and allow motions down and up to be sequenced nicely with minimal boilerplate, as in the state monad. Maybe I'll find those and fill in this section properly.
Any help? I thought cabal-dev was supposed to solve these sort of problems?
Trying to install Ed Kmett's category-extras package and ran into this:
$ cabal-dev install category-extras Resolving dependencies... cabal: Could not resolve dependencies: trying: category-extras-1.0.2 trying: representable-functors-3.0.1 trying: mtl-2.1.1/installed-801... trying: pointed-3.0.2 rejecting: indexed-extras-0.1.1 (conflict: pointed==3.0.2, indexed-extras => pointed<2.2) rejecting: indexed-extras-0.1 (conflict: mtl==2.1.1/installed-801..., indexed-extras => mtl<2.1)
submitted by peterjoel[link] [8 comments]
Some aggregation of Haskell content
Github incorrectly recognizes haskell code as perl thus making language usage studies based on github useless.
I cannot compile ghc-7.6.2
Dominic Steinitz: Parallelising Path Dependent Options in Haskell
Now we are able to price options using parallelism, let us consider a more exotic financial option.
Let us suppose that we wish to price an Asian call option. The payoff at time is
Thus the payoff depends not just on the value of the underlying at time but also on the path taken. We do not need to know the entire path, just the average at discrete points in time. Thus the payoff is a function of time, the value of the underlying and the average of the underlying sampled at discrete points in time .
We can rewrite this equation as a recursive relation:
If is the -th sampling time then for small let:
Now we can write the equation for the value of the average just before and after the sampling time as:
Since there is no arbitrage, the value of the option cannot change as it crosses the sampling date:
Substituting in:
But we have a problem, we do not know the value of . Away from the sampling times there is no dependence on as its value cannot change. We already know how to step back in time in this case: we use the pricer we have already developed.
So let us assume a value for . Then we can diffuse backwards from the final payoff but when we reach a sampling date, we reset the values on the grid using the interfacing formula above.
In summary, we assume a set of values for and then diffuse backwards for each pricer with that ; at each sampling time, we reset the values of the pricers and continue until we reach the last sampling time. At this point, so we diffuse one pricer back to the start time which gives us the price of the option for any given on our grid.
Our usual imports and options.
> {-# LANGUAGE FlexibleContexts #-} > {-# LANGUAGE TypeOperators #-} > {-# LANGUAGE NoMonomorphismRestriction #-} > > {-# OPTIONS_GHC -Wall #-} > {-# OPTIONS_GHC -fno-warn-name-shadowing #-} > {-# OPTIONS_GHC -fno-warn-type-defaults #-} > > import Data.Array.Repa as Repa hiding ((++), map) > import Control.Monad > import AsianDiagram > import Diagrams.Prelude((===)) > import Diagrams.Backend.Cairo.CmdLine > import Text.Printf > import Data.ListFirst some constants for the payoff and the pricer. We make the space grid deliberately coarse so we can draw diagrams showing the grid before and after interfacing.
> r, sigma, k, t, xMax, aMax, deltaX, deltaT, deltaA:: Double > m, n, p :: Int > r = 0.05 > sigma = 0.2 > k = 50.0 > t = 3.0 > m = 10 > p = 10 > xMax = 150 > deltaX = xMax / (fromIntegral m) > aMax = 150 > deltaA = aMax / (fromIntegral p) > n = 100 > deltaT = t / (fromIntegral n)We take the times at which do our Asian observations and calculate the number of steps between each observation including the initial and terminal times.
> asianTimes :: [Int] > asianTimes = map (\x -> floor $ x*(fromIntegral n)/t) [1.5,2.0,2.5] > > numSteps :: [Int] > numSteps = snd $ mapAccumL (\s x -> (x, x - s)) 0 times > where times = asianTimes ++ [n]As before we can define a single pricer that updates the grid over one time step and at multiple points in space using the Explicit Euler method. We parameterize the upper and lower boundaries and as we will want to use our pricer not just for a vanilla call option.
> type BoundaryCondition = Array D DIM1 Double -> Double > > singleUpdater :: BoundaryCondition -> > BoundaryCondition -> > Array D DIM1 Double -> > Array D DIM1 Double > singleUpdater lb ub arr = traverse arr id f > where > Z :. m = extent arr > f _get (Z :. ix) | ix == 0 = lb arr > f _get (Z :. ix) | ix == m-1 = ub arr > f get (Z :. ix) = a * get (Z :. ix-1) + > b * get (Z :. ix) + > c * get (Z :. ix+1) > where > a = deltaT * (sigma^2 * x^2 - r * x) / 2 > b = 1 - deltaT * (r + sigma^2 * x^2) > c = deltaT * (sigma^2 * x^2 + r * x) / 2 > x = fromIntegral ixAgain we can extend this to update many pricers on one time step and multiple points in space.
> multiUpdater :: Source r Double => > BoundaryCondition -> > BoundaryCondition -> > Array r DIM2 Double -> > Array D DIM2 Double > multiUpdater lb ub arr = fromFunction (extent arr) f > where > f :: DIM2 -> Double > f (Z :. ix :. jx) = (singleUpdater lb ub x)!(Z :. ix) > where > x :: Array D DIM1 Double > x = slice arr (Any :. jx)We define the boundary condition at the maturity date of our Asian option. Notice for each pricer the boundary condition is constant, this being determined by the value of the Asian payoff.
> priceAtTAsian :: Array U DIM2 Double > priceAtTAsian = fromListUnboxed (Z :. m+1 :. p+1) > [ max 0 (deltaA * (fromIntegral l) - k) > | _j <- [0..m], > l <- [0..p] > ]With this we can step backwards in time for any number of timesteps.
> stepMulti :: Monad m => > Int -> > BoundaryCondition -> > BoundaryCondition -> > Array U DIM2 Double -> > m (Array U DIM2 Double) > stepMulti n lb ub = updaterM > where > updaterM :: Monad m => Array U DIM2 Double -> > m (Array U DIM2 Double) > updaterM = foldr (>=>) return updaters > where > updaters = replicate n (computeP . multiUpdater lb ub) Boundary ConditionsBut now we are stuck. What are the boundary conditions for each of the pricers after we have done our interfacing? We follow many practioners and assume that the underlying is linear in this area. Thus in the Black-Scholes equation
we set the second derivative to . Thus we can use a forward method at the boundary to solve the equation below.
When , we have a simpler situation.
The corresponding difference equation for the lower boundary is:
Which is easily represented in Haskell (rembering we are stepping backwards in time).
> lBoundaryUpdater :: BoundaryCondition > lBoundaryUpdater arr = x - deltaT * r * x > where > x = arr!(Z :. (0 :: Int))The corresponding difference equation for the upper boundary is:
Re-arranging
We can write this in Haskell as follows (again remembering we are stepping backwards in time).
> uBoundaryUpdater :: BoundaryCondition > uBoundaryUpdater arr = x - deltaT * r * (a - b) > where > Z :. m = extent arr > x = arr!(Z :. m - 1) > y = arr!(Z :. m - 2) > a = x * fromIntegral (m - 1) > b = y * fromIntegral m InterfacingWe interface by linear interpolation if value we require lies between 2 points on our grid otherwise we use linear extrapolation.
> interface :: Int -> Array U DIM2 Double -> > Array D DIM2 Double > interface n grid = traverse grid id (\_ sh -> f sh) > where > (Z :. _iMax :. jMax) = extent grid > f (Z :. i :. j) = inter > where > x = deltaX * (fromIntegral i) > aPlus = deltaA * (fromIntegral j) > aMinus = aPlus + (x - aPlus) / (fromIntegral n) > jLower = if k > jMax - 1 then jMax - 1 else k > where k = floor $ aMinus / deltaA > jUpper = if (jLower == jMax - 1) > then jMax - 1 > else jLower + 1 > aLower = deltaA * (fromIntegral jLower) > prptn = (aMinus - aLower) / deltaA > vLower = grid!(Z :. i :. jLower) > vUpper = grid!(Z :. i :. jUpper) > inter = vLower + prptn * (vUpper - vLower) ExampleNow we are in a position to give an example of pricing our option with a few helper functions
> showD :: Double -> String > showD = printf "%.2f" > > showArrD1 :: Array U DIM1 Double -> String > showArrD1 = intercalate ", " . map showD . toList > > showSlices :: String -> Array U DIM2 Double -> IO () > showSlices message prices = do > putStrLn ('\n' : message) > > let (Z :. _i :. j) = extent prices > slicesD = map (\m -> slice prices (Any :. m)) [0..j-1] > > slices <- mapM computeP slicesD > mapM_ (putStrLn . showArrD1) slices > > diagonal :: Source a Double => > Array a DIM2 Double -> > Array D DIM2 Double > diagonal arr = traverse arr g f > where > f :: (DIM2 -> Double) -> DIM2 -> Double > f get (Z :. ix :. _) = get (Z :. ix :. ix) > > g :: DIM2 -> DIM2 > g (Z :. ix :. iy) = Z :. (min ix iy) :. (1 :: Int) > > main :: IO () > main = do putStrLn "\nAsianing times" > putStrLn $ show asianTimes > > let lb = lBoundaryUpdater > ub = uBoundaryUpdater > > showSlices "Initial pricers" priceAtTAsianNow instead of stepping all the way back to the initial time of the option, we only step back to just before the last observation.
> grid3b <- stepMulti (numSteps!!3) lb ub priceAtTAsian > showSlices ("Just before 3") grid3bThe diagram below shows our grid just before we make the last observation. The -axis is the value of the underlying and the -axis is the value of the Asian value. Both have been normalised to 1.0. That is the value 1.0 represents 150.0 (our maximum value on the grid for both the underlying and the Asian / auxiliary variable).
> grid3a <- computeP $ interface 3 grid3b > showSlices ("Just after 3") grid3aThe diagram below shows our grid after before we make the last observation i.e., after interfacing. Again, the -axis is the value of the underlying and the -axis is the value of the Asian value. Both have been normalised to 1.0. That is the value 1.0 represents 150.0 (our maximum value on the grid for both the underlying and the Asian / auxiliary variable).
And then step backwards with the new final boundary condition.
> grid2b <- stepMulti (numSteps!!2) lb ub grid3a > showSlices ("Just before 2") grid2b > > grid2a <- computeP $ interface 2 grid2b > showSlices ("Just after 2") grid2aAgain we step backwards in time with a new final boundary condition.
> grid1b <- stepMulti (numSteps!!1) lb ub grid2a > showSlices ("Just before 1") grid1bFinally we step all the way back to the time at which we wish to know the price. Here the interface condition is just so we can take the diagonal of our grid and diffuse backwards using a single pricer.
> grid1a <- computeP $ diagonal grid1b > showSlices ("Just after 1") grid1a > grid1b <- stepMulti (numSteps!!0) lb ub grid1a > showSlices "Final pricer" grid1bMonads vs. Actors | Lambda the Ultimate
Edwin Brady: Idris, a General Purpose Dependently Typed Programming Language: Design and Implementation
I’m busy revising the “How Idris works” paper, and you can find the latest draft here. Any further comments on how to improve it would be most welcome! Abstract:
Many components of a dependently typed programming language are by now well understood, for example the underlying type theory, type checking, unification and evaluation. How to combine these components into a realistic and usable high level language is, however, folklore, discovered anew by successive language implementations. In this paper, I describe the implementation of a new dependently typed functional programming language, IDRIS. IDRIS is intended to be a general purpose programming language and as such provides high level concepts such as implicit syntax, type classes and do notation. I describe the high level language and the underlying type theory, and present a method for elaborating concrete high level syntax with implicit arguments and type classes into a fully explicit type theory. Furthermore, I show how this method, based on a domain specific language embedded in Haskell, facilitates the implementation of new high level language constructs.
I've created a "Haskell" Vimeo channel
I discovered an Haskell channel on Vimeo but last update was 3 years ago. It's a shame, because that, combined with the fact there are a lot of false positives when searching for "Haskell", I sometimes struggle to find something relevant, so a lot of cool Haskell videos posted here simply get forgot (at least, I tend to forget about them, simply because I'm on my iPad and I'm too lazy to login on Vimeo and add the video to my favourite one / watch later). Put this with the fact that not everyone has a Vimeo account, for this last time of users there's almost no way to find the videos later (well, you can use the old school Bookmarks/Read it Later but I tend to forget about stuff I put in there :D )
In a nutshell, I've created this channel here:
https://vimeo.com/channels/472404
It's a shame to have such a duplication though, so if someone has the contact of the original channel moderator I will be more than happy than do a bit of housekeeping and to add a bit of more recent content. I've also decided to give the channel a different name, to make it more explicit during searches. For now I've added just a bunch of cool videos from the NYC Haskell meetup, but if you send me as PM your video links I'll add them for you.
At the end of the day I'm sorry for the duplication on Vimeo, and I hope we can have an updated, modern channel to collect stuff, but I've created this channel primary for me as container of useful stuff and I though it could have been useful also for someone else :)
submitted by CharlesStain[link] [7 comments]