Skip to main content

Home/ Haskell/ Group items tagged list

Rss Feed Group items tagged

J.A. Alonso

Purely Functional Algorithm Specification ~ Jan van Eijck - 0 views

  •  
    This course offers a perspective on algorithm specification, in terms of purely functional programming. An algorithm is an effective method expressed as a list of instructions describing a computation for calculating a result. Algorithms have to be written in human readable form, either using pseudocode (natural language looking like executable code), a high level specification language like Dijkstra's Guarded Command Language, or an executable formal specification formalism such as Z. The course will develop a purely functional perspective on algorithm specification, and demonstrate how this can be used for specifying (executable) algorithms, and for automated testing of Hoare correctness statements about these algorithms. The small extension of Haskell that we will present and discuss can be viewed as a domain specific language for algorithm specification and testing. Inspiration for this was the talk by Leslie Lamport at CWI on the executable algorithm specification language PlusCal plus Edsger W. Dijkstra, "EWD472: Guarded commands, non-determinacy and formal derivation of programs." Instead of formal program derivation, we demonstrate test automation of Hoare style assertions.
Javier Neira

Understanding Monads Via Python List Comprehensions « All Unkept - 0 views

  • But here we have taken it to a higher level -- the Monad interface is like an abstraction of any kind of container.
  • This in turn leads to the concept that a monadic value represents a computation -- a method for computing a value, bound together with its input value.
  • Writing monads is hard, but it pays off as using them in Haskell is surprisingly easy, and allows you to do some very powerful things.
  • ...3 more annotations...
  • One of them you have seen explicitly -- it's the 'return' method, responsible for packing things up into the monad. The other is called 'bind' or '>>=', and it does the 'unpacking' involved with the <- arrow in the do notation.
  • the 'bind' method doesn't really unpack and return the data. Instead, it is defined in such a way that it handles all unpacking 'internally', and you have to provide functions that always have to return data inside the monad.
  • It looks very much like 'unpack this data from the monad so I can use it', so it helps conceptually. In fact, together with the rest of the body of the 'do' block it forms an anonymous lambda function,
Javier Neira

A Neighborhood of Infinity: The IO Monad for People who Simply Don't Care - 0 views

  • Many programming languages make a distinction between expressions and commands.
  • Like other languages it makes the distinction, and like other languages it has its own slightly idiosyncratic notion of what the difference is. The IO monad is just a device to help make this distinction.
  • There is no room for anything like a print command here because a print command doesn't return a value, it produces output as a side-effect
  • ...18 more annotations...
  • It's easy to use: you just write do and then follow it by an indented list of commands. Here's a complete Haskell program:
  • Note also that commands take arguments that can be expressions. So print (2*x) is a command, but 2*x is an expression. Again, little different from a language like Python.
  • So here's an interesting feature of Haskell: commands can return values. But a command that returns a value is different from an expression with a value.
  • We have to use <- instead of let ... = ... to get a returned value out of a command. It's a pretty simple rule, the only hassle is you have to remember what's a command and what's a function.
  • get2Lines = do line1 <- getLine line2 <- getLine return (line1,line2)
  • To introduce a list of commands, use do.To return a value from a command, use return.To assign a name to an expression inside a do block use let.To assign a name to the result of a command, use <-.
  • what's a command and what's an expression? If it has any chance of doing I/O it must be a command, otherwise it's probably an expression.
  • Everything in Haskell has a type, even commands. In general, if a command returns a value of type a then the command itself is of type IO a.
  • eturn is simply a function of type a -> IO a that converts a value of type a to a command of type IO a.
  • 5. The type of a sequence of commands is the type of the last line.
  • The type of an if statement is the type of its branches. So if you want an if statement inside a do block, it needs to be a command, and so its branches need to be commands also. So it's
  • If something is of type IO a then it's a command returning an value of type a. Otherwise it's an expression. That's the rule.
  • following the rules above it's completely impossible to put an executed command inside an expression.
  • As the only way to do I/O is with commands, that means you have no way to find out what Haskell is doing inside expressions.
  • If the type isn't IO a, then you can sleep at night in the confidence that there are no side effects.
  • One last thing. Much of what I've said above is false. But what I hope I have done is describe a subset of Haskell in which you can start some I/O programming without having a clue what a monad is.
  • The idea of capturing imperative computations in a type of (immutable) values is lovely. And so is the general pattern we call "monad".
  • main = do return 1 print "Hello"
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) => Obj a   xs :: [Obj] xs = [Obj 1, Obj "foo", Obj 'c']   doShow :: [Obj] -> String doShow [] = "" doShow ((Obj x):xs) = show x ++ doShow xs With output: doShow xs ==> "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  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), 0) | i <- [1..n]] is the same matrix, except with the diagonal zeroed.
  • -- A rectangular subarray subArray :: (Ix a) => (a,a) -> Array a b -> Array a b subArray bnds = ixmap bnds (\i->i) -- A row of a matrix row :: (Ix a, Ix b) => a -> Array (a,b) c -> Array b c row i x = ixmap (l',u') (\j->(i,j)) x where ((_,l'),(_,u')) = bounds x -- Diagonal of a matrix (assumed to be square) diag :: (Ix a) => Array (a,a) b -> Array a b diag x = ixmap (l,u) (\i->(i,i)) x        where           ((l,_),(u,_)) = bounds x -- Projection of first components of an array of pairs firstArray :: (Ix a) => Array a (b,c) -> Array a b firstArray = fmap (\(x,y)->x)
Javier Neira

99 questions/1 to 10 - HaskellWiki - 0 views

  • data NestedList a = Elem a | List [NestedList a]   flatten :: NestedList a -> [a] flatten (Elem x) = [x] flatten (List x) = concatMap flatten x
  • compress :: Eq a => [a] -> [a] compress = map head . group We simply group equal values together (group), then take the head of each. Note that (with GHC) we must give an explicit type to compress otherwise we get:
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

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 (>>=)
1 - 11 of 11
Showing 20 items per page