Skip to main content

Home/ Haskell/ Group items tagged example

Rss Feed Group items tagged

Javier Neira

A Neighborhood of Infinity: Haskell Monoids and their Uses - 0 views

  • The Writer MonadYou can think of monoids as being accumulators. Given a running total, n, we can add in a new value a to get a new running total n' = n `mappend` a. Accumulating totals is a very common design pattern in real code so it's useful to abstract this idea. This is exactly what the Writer monad allows. We can write monadic code that accumulates values as a "side effect". The function to perform the accumulation is (somewhat confusingly) called tell. Here's an example where we're logging a trace of what we're doing.
  • This is an implementation of the factorial function that tells us what it did.
  • We use runWriter to extract the results back out. If we run> ex1 = runWriter (fact1 10)we get back both 10! and a list of what it took to compute this.
  • ...6 more annotations...
  • and the monoid for addition is Sum
  • but there is a big advantage to using the Writer version. It has type signature f :: Integer -> Writer (Sum Integer) Integer. We can immediately read from this that our function has a side effect that involves accumulating a number in a purely additive way.
  • This is the Bool type with the disjunction operator, better known as ||.
  • "tell my caller if any value of r is ever 120"
  • One last application to mention is the Data.Foldable library. This provides a generic approach to walking through a datastructure, accumulating values as we go. The foldMap function applies a function to each element of our structure and then accumulates the return values of each of these applications. An implementation of foldMap for a tree structure might be
  • Suppose we want to accumulate two side effects at the same time. For example, maybe we want to both count instructions and leave a readable trace of our computation. We could use monad transformers to combine two writer monads. But there is a slightly easier way - we can combine two monoids into one 'product' monoid. It's defined like this:instance (Monoid a,Monoid b) => Monoid (a,b) where mempty = (mempty,mempty) mappend (u,v) (w,x) = (u `mappend` w,v `mappend` x)
Javier Neira

Haskell: The Confusing Parts - 0 views

  • f $ x = f x(f . g) x = f (g x)-- Some quick examples of using these. The following line...putStrLn (take 12 (map foo (bar ++ "ack")))-- ...can be rewritten as...putStrLn $ take 12 $ map foo $ bar ++ "ack"(putStrLn . take 12 . map foo) (bar ++ "ack")putStrLn . take 12 . map foo $ bar ++ "ack" In terms of good Haskell style, the last example above is preferable to the others. By the way, note that ($) has the lowest precedence (zero) of any operator, so you can almost always use arbitrary syntax on either side of it.
  • -- Actual definitions:f $ x = f x(f . g) x = f (g x)-- Some quick examples of using these. The following line...putStrLn (take 12 (map foo (bar ++ "ack")))-- ...can be rewritten as...putStrLn $ take 12 $ map foo $ bar ++ "ack"(putStrLn . take 12 . map foo) (bar ++ "ack")putStrLn . take 12 . map foo $ bar ++ "ack"
  • putStrLn (take 12 (map foo (bar ++ "ack")))-- ...can be rewritten as...putStrLn $ take 12 $ map foo $ bar ++ "ack"(putStrLn . take 12 . map foo) (bar ++ "ack")putStrLn . take 12 . map foo $ bar ++ "ack"
  • ...7 more annotations...
  • putStrLn (take 12 (map foo (bar ++ "ack")))
  • anywhere you might write \x -> foo x [1..10], you should instead write flip foo [1..10], where flip is a standard Prelude function that flips the first two arguments of whatever function you give it
  • two arguments of whatever
  • anywhere you might write \x -> foo x [1..10], you should instead write flip foo [1..10], where flip is a standard Prelude function that flips the first
  • The curry and uncurry functions stand in for \f x y -> f (x, y) and \f (x, y) -> f x y, respectively.
  • The curry and uncurry functions stand in for \f x y -> f (x, y)
  • I will point out that return is, in fact, not a return statement. It’s a function, and an inappropriately named function, at that. Writing return () in your do block will not cause the function to return.
  •  
    If you're used to the C family of languages, or the closely related family of "scripting languages," Haskell's syntax (mainly) is a bit baffling at first. For some people, it can even seem like it's sneaking out from under you every time you think you understand it. This is sort of a FAQ for people who are new to Haskell, or scared away by its syntax.
J.A. Alonso

Programming errors in traversal programs over structured data - 0 views

  •  
    Traversal strategies `a la Stratego (also `a la Strafunski and 'Scrap Your Boilerplate') provide an exceptionally versatile and uniform means of querying and transforming deeply nested and heterogeneously structured data including terms in functional programming and rewriting, objects in OO programming, and XML documents in XML programming. However, the resulting traversal programs are prone to programming errors. We are specifically concerned with errors that go beyond conservative type errors; examples we examine include divergent traversals, prematurely terminated traversals, and traversals with dead code. Based on an inventory of possible programming errors we explore options of static typing and static analysis so that some categories of errors can be avoided. This exploration generates suggestions for improvements to strategy libraries as well as their underlyingq programming languages. Haskell is used for illustrations and specifications with sufficient explanations to make the presentation comprehensible to the non-specialist. The overall ideas are language-agnostic and they are summarized accordingly.
Javier Neira

Fatvat: Web Sockets and Haskell - 0 views

  •  
    import Network import System.IO import Control.Concurrent import Char serverHandshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n\ \Upgrade: WebSocket\r\n\ \Connection: Upgrade\r\n\ \WebSocket-Origin: http://localhost\r\n\ \WebSocket-Location: ws://localhost:9876/\r\n\ \WebSocket-Protocol: sample\r\n\r\n\0" acceptLoop socket = forever $ do (h,_,_) IO () listenLoop h = do sendFrame h "hello from haskell" threadDelay (3 * 1000000) sendFrame h "it works!" return () sendFrame :: Handle -> String -> IO () sendFrame h s = do hPutChar h (chr 0) hPutStr h s hPutChar h (chr 255)
Javier Neira

Monads as containers - HaskellWiki - 0 views

  • A monad is a container type together with a few methods defined on it.
  • all the elements which a monadic container holds at any one time must be the same type (it is homogeneous).
  • map (fmap), return and join,
  • ...15 more annotations...
  • map, (but called fmap in Haskell 98) actually comes from the definition of a functor
  • That is, if f is a functor, and we are given a function of type (a -> b), and a container of type (f a), we can get a new container of type (f b). This is expressed in the type of fmap: fmap :: (Functor f) => (a -> b) -> f a -> f b If you will give me a blueberry for each apple I give you (a -> b), and I have a box of apples (f a), then I can get a box of blueberries (f b). Every monad is a functor.
  • The second method, return, is specific to monads. If m is a monad, then return takes an element of type a, and gives a container of type (m a) with that element in it. So, its type in Haskell is return :: (Monad m) => a -> m a If I have an apple (a) then I can put it in a box (m a).
  • takes a container of containers m (m a), and combines them into one m a in some sensible fashion. Its Haskell type is join :: (Monad m) => m (m a) -> m a
  • If I have a box of boxes of apples (m (m a)) then I can take the apples from each, and put them in a new box (m a).
  • bind or extend, which is commonly given the symbol (>>=)
  • liftM :: (Monad m) => (a -> b) -> m a -> m b liftM f xs = xs >>= (return . f) -- take a container full of a's, to each, apply f, -- put the resulting value of type b in a new container, -- and then join all the containers together.
  • The function that does this for any monad in Haskell is called liftM -- it can be written in terms of return and bind as follows:
  • Well, in Haskell, IO is a monad.
  • Lists are most likely the simplest, most illustrative example
  • The reason that bind is so important is that it serves to chain computations on monadic containers together.
  • You might notice a similarity here between bind and function application or composition, and this is no coincidence.
  • What bind does is to take a container of type (m a) and a function of type (a -> m b). It first maps the function over the container, (which would give an m (m b)) and then applies join to the result to get a container of type (m b). Its type and definition in Haskell is the
  • xs >>= f = join (fmap f xs)
  • bind (>>=)
Javier Neira

Understanding Haskell Monads - 0 views

  • The opposite of referentially transparent is referentially opaque. A referentially opaque function is a function that may mean different things and return different results each time, even if all arguments are the same.
  • a function that just prints a fixed text to the screen and always returns 0, is referentially opaque, because you cannot replace the function call with 0 without changing the meaning of the program.
  • n fact, a function, which doesn't take any arguments, isn't even a function in Haskell. It's simply a value. A number of simple solutions to this problem exist. One is to expect a state value as an argument and produce a new state value together with a pseudorandom number: random :: RandomState -> (Int, RandomState)
  • ...12 more annotations...
  • A general purpose language is almost useless, if you can't develop user interfaces or read files. We would like to read keyboard input or print things to the terminal.
  • We have seen that we can solve this problem by expecting a state argument. But what's our state? The state of the terminal?
  • We seem to have found a useful solution to our problem. Just pass the state value around. But there is a problem with this approach.
  • A very special feature of Haskell is the concept of generalization. That means, instead of implementing an idea directly, you rather try to find a more general idea, which implies your idea as a special case.
  • However, the traditional programmer never had to face generalization. At most they faced abstraction,
  • they are a very abstract structure, which allows implementing functionality at an incredibly general level.
  • Haskell [1] is a purely functional programming language. Functions written in it are referentially transparent. Intuitively that means that a function called with the same arguments always gives the same result.
  • askell takes another approach. Instead of passing the world state explicitly, it employs a structure from category theory called a monad.
  • They are an abstract structure, and at first it can be difficult to understand where they are useful. The two main interpretations of monads are as containers and as computations.
  • The ⊥ value is a theoretical construct. It's the result of a function, which never returns, so you can't observe that value directly. Examples are functions, which recurse forever or which throw an exception. In both cases, there is no ordinary returning of a value.
  • Now that Nothing is a valid result, our function handles all cases.
  • You have some computation with a certain type of result and a certain structure in its result (like allowing no result, or allowing arbitrarily many results), and you want to pass that computation's result to another computation.
Javier Neira

jaspervdj - Maybe, null, and boilerplate code - 0 views

  • A first goal they serve is as "unassigned variables". I will not cover that here, instead I will focus on another use: abnormal return values.
  • So, null is some sort of "Not found" error here. But wait - they could have used an Exception here!
  • We see a similar behavior here: when the object is found, we get a Just a, and when it is not found, we get Nothing - comparable to a null pointer.
  • ...5 more annotations...
  • So, while we can get a null back from a function, we should never give it to a function.
  • Now, if you have written a lot of Java code, you know that checking for null is a vital part of the job, and fragments like the one above are pretty common.
  • In Haskell, however, Maybe is also a monad - and monads can be used to prevent common patterns in code - in other words, they assist you in the D.R.Y.-principle2. We can therefore write the above snippet again using do-notation3.
  • getPathMonth :: Map String String -> Maybe MonthgetPathMonth m = do p <- lookup "path" m d <- parseDate p return $ getMonth d
  • he whole "check-for-null-and-short-circuit" behavior is defined by the Maybe monad -
  •  
    getPathMonth :: Map String String -> Maybe Month getPathMonth m = case M.lookup "path" m of Nothing -> Nothing (Just p) -> case parseDate p of Nothing -> Nothing (Just d) -> Just (getMonth d) getPathMonth :: Map String String -> Maybe Month getPathMonth m = do p <- parseDate p return $ getMonth d
Javier Neira

Existential type - HaskellWiki - 0 views

  • First of all, it is now impossible for a function to demand a Worker having a specific type of buffer. Second, the type of foo can now be derived automatically without needing an explicit type signature. (No monomorphism restriction.) Thirdly, since code now has no idea what type the buffer function returns, you are more limited in what you can do to it.
  • This illustrates creating a heterogeneous list, all of whose members implement "Show", and progressing through that list to show these items: data Obj = forall a. (Show a) =&gt; Obj a &nbsp; xs :: [Obj] xs = [Obj 1, Obj "foo", Obj 'c'] &nbsp; doShow :: [Obj] -&gt; String doShow [] = "" doShow ((Obj x):xs) = show x ++ doShow xs With output: doShow xs ==&gt; "1\"foo\"'c'"
  • Existential types in conjunction with type classes can be used to emulate the dynamic dispatch mechanism of object oriented programming languages. To illustrate this concept I show how a classic example from object oriented programming can be encoded in Haskell.
Javier Neira

The Haskell 98 Library Report: Arrays - 0 views

  • 16.2&nbsp;&nbsp;Incremental Array Updates The operator (//) takes an array and a list of pairs and returns an array identical to the left argument except that it has been updated by the associations in the right argument. (As with the array function, the indices in the association list must be unique for the updated elements to be defined.) For example, if m is a 1-origin, n by n matrix, then m//[((i,i),&nbsp;0)&nbsp;|&nbsp;i&nbsp;&lt;-&nbsp;[1..n]] is the same matrix, except with the diagonal zeroed.
  • --&nbsp;A&nbsp;rectangular&nbsp;subarray subArray&nbsp;::&nbsp;(Ix&nbsp;a)&nbsp;=&gt;&nbsp;(a,a)&nbsp;-&gt;&nbsp;Array&nbsp;a&nbsp;b&nbsp;-&gt;&nbsp;Array&nbsp;a&nbsp;b subArray&nbsp;bnds&nbsp;=&nbsp;ixmap&nbsp;bnds&nbsp;(\i-&gt;i) --&nbsp;A&nbsp;row&nbsp;of&nbsp;a&nbsp;matrix row&nbsp;::&nbsp;(Ix&nbsp;a,&nbsp;Ix&nbsp;b)&nbsp;=&gt;&nbsp;a&nbsp;-&gt;&nbsp;Array&nbsp;(a,b)&nbsp;c&nbsp;-&gt;&nbsp;Array&nbsp;b&nbsp;c row&nbsp;i&nbsp;x&nbsp;=&nbsp;ixmap&nbsp;(l',u')&nbsp;(\j-&gt;(i,j))&nbsp;x&nbsp;where&nbsp;((_,l'),(_,u'))&nbsp;=&nbsp;bounds&nbsp;x --&nbsp;Diagonal&nbsp;of&nbsp;a&nbsp;matrix&nbsp;(assumed&nbsp;to&nbsp;be&nbsp;square) diag&nbsp;::&nbsp;(Ix&nbsp;a)&nbsp;=&gt;&nbsp;Array&nbsp;(a,a)&nbsp;b&nbsp;-&gt;&nbsp;Array&nbsp;a&nbsp;b diag&nbsp;x&nbsp;=&nbsp;ixmap&nbsp;(l,u)&nbsp;(\i-&gt;(i,i))&nbsp;x &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;((l,_),(u,_))&nbsp;=&nbsp;bounds&nbsp;x --&nbsp;Projection&nbsp;of&nbsp;first&nbsp;components&nbsp;of&nbsp;an&nbsp;array&nbsp;of&nbsp;pairs firstArray&nbsp;::&nbsp;(Ix&nbsp;a)&nbsp;=&gt;&nbsp;Array&nbsp;a&nbsp;(b,c)&nbsp;-&gt;&nbsp;Array&nbsp;a&nbsp;b firstArray&nbsp;=&nbsp;fmap&nbsp;(\(x,y)-&gt;x)
1 - 16 of 16
Showing 20 items per page