Re: [Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread Ivan Miljenovic
On 26 July 2010 16:33, David Virebayre  wrote:
> On Sun, Jul 25, 2010 at 11:53 PM, Edward Z. Yang  wrote:
>
>> An interesting alternate spin on flip is infix notation combined with partial
>> application, such as:
>>
>>    (`foobar` 3)
>>
>> which is equivalent to
>>
>>    \x -> foobar x 3
>>
>> I frequently use this, although the jury's out on whether or not it's more 
>> readable.
>
> I had HLint suggest me this :
>
> before :
>
> listeEtagTot = concatMap (flip listeEtagArm cfgTypesTringle) listeArmOrd
>
> after :
>
> listeEtagTot = concatMap (`listeEtagArm` cfgTypesTringle) listeArmOrd

However, if you had something like this, I think the flip version is nicer:

With flip:

foo = map (f . flip g x)

Without flip:

foo = map (f . (`g` x))

-- 
Ivan Lazar Miljenovic
ivan.miljeno...@gmail.com
IvanMiljenovic.wordpress.com
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread David Virebayre
On Sun, Jul 25, 2010 at 11:53 PM, Edward Z. Yang  wrote:

> An interesting alternate spin on flip is infix notation combined with partial
> application, such as:
>
>    (`foobar` 3)
>
> which is equivalent to
>
>    \x -> foobar x 3
>
> I frequently use this, although the jury's out on whether or not it's more 
> readable.

I had HLint suggest me this :

before :

listeEtagTot = concatMap (flip listeEtagArm cfgTypesTringle) listeArmOrd

after :

listeEtagTot = concatMap (`listeEtagArm` cfgTypesTringle) listeArmOrd


David.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Iteratee package: combining enumerators

2010-07-25 Thread Max Cantor
I have a series of files with binary encoded data in them, and want to create 
an enumerator iterates on the first element at the front of all the files.  
Something like the pseudocode: return . minimum =<< mapM (fmap (heads . lines) 
readFile)  listOfFileNames

I can use convStream to create an enumerator which runs iteratees on each tuple 
in a single file:

(convStream decodeStrings) :: Monad m => IterateeG [] String m a -> IterateeG 
WrappedByteString Word8 m (IterateeG [] MyDataType m a)

or, with the EnumerateeGMM tysyn:

(convStream decodeStrings) :: Monad m => EnumerateeGMM WrappedByteString Word8 
[] String m a 

My question is if there is a simple way to combine the Enumeratees to enumerate 
on a set of files or if I have to write an enumerator from scratch.

Thank you in advance,
Max

P.S. John, apologies for the duped email, sent from the wrong address by 
mistake.___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Richard O'Keefe

On Jul 26, 2010, at 12:35 PM, John Lato wrote:
> Incidentally, there seems to be a consensus that this a Bad Idea [1].
> Even when you specify a type class context on a data declaration,
> Haskell still requires you to specify the context on functions that
> use that data (Address c a).

This has always puzzled me.

Take the obvious
data Ord key
  => BST key val
   = Empty
   | Node key val (BST key val) (BST key val)

Why would anyone say this if they didn't *want* the constraint
implied on every use?  If you want the constraint implied on
every use of any constructor, including ones where the constructor
is used for pattern matching, what do you do if not this?

Good software engineering involves *controlled* use of redundancy.
Having it *stated* in one place and *checked* in others is an
example.  Requiring the same information to be repeated everywhere
is not.

>  What's worse is that you need the class
> restriction for *all* functions that use an Address,

and if you didn't WANT that, you wouldn't say this.

Oh sure, something like
is_empty (Empty)= True
is_empty (Node _ _ _ _) = Fase
doesn't happen to make use of any constrained component.
But it is part of a *group* of methods which collectively
don't make any sense without it, so there's no real practical
advantage to having some functions constrained and some not
(unless you count delaying error message as an advantage).

> 
> and don't export the Address data constructor.

This doesn't help _within_ the defining module where you
are pattern matching.

In "stupid theta", the only stupidity would seem to be refusing
to honour the programmer's evident intent.  It's rather like
saying "Oh the programmer said this constructor argument must
be an Int, but I'll require him to repeat that everywhere".



___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: Re[Haskell-cafe] ad large file and match lines to a pattern

2010-07-25 Thread Ivan Miljenovic
On 26 July 2010 00:48, grzyb  wrote:
>
> Hi,
>
> I'm a beginner in haskell, I was trying to write the following code, but I
> still encourage some problems, can you help me with that?
>
> I need to read a large file and try to match each line to a pattern which is
> int,int value="string"
> for example:
> 0,1 value="string1"
> 1,5 value="string2"
> when the line matches the pattern then I need to get those 3 values (int,
> int, string) and pass them to my function.

Whilst you can probably use the ReadS (or ReadP if you don't care
about backwards compatability) parsers for the Read class to do this,
I highly recommend you instead learn and use a proper parsing library
such as parsec, polyparse or uuparsing-lib for this (as you'll
undoubtedly be wanting to do more extensive parsing at a later date).

-- 
Ivan Lazar Miljenovic
ivan.miljeno...@gmail.com
IvanMiljenovic.wordpress.com
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Techniques for ensuring parser correctness?

2010-07-25 Thread Jason Dagit
Hello,

I find that parser correctness is often hard to verify.  Therefore, I'm
interested in techniques that others have used successfully, especially with
Haskell.

Techniques I'm aware of:
  * Round trip checks: Generate a datastructure, render as a string, parse
back, and compare.  Quickcheck can be used to automate this.
  * Fuzz testing:  What tools exist to help me?
  * Formal verification: Has anyone been using this with Haskell parsers?
 Other than general theorem provers, say Isabelle, what tools exist?

My specific need:
The immediate challenge I have is that I'm modifying the parser that Darcs
uses and we would like to improve the parser's test suite as well.  The
parser abstraction used in this case follows parsec's API.  Left to my own
devices I would use round trip checks, written with quickcheck, for this
exercise.  Because we're using a parsec style parser, I don't have a nice
neat grammar handy.

Thanks in advance for any advice you have!

Thanks,
Jason
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread John Lato
> From: Patrick Browne 
>
> Andrew,
> Thanks for your detailed feedback, it is a great help.
> I appreciate that the code does not do anything useful, nor is it an
> appropriate way to write Haskell, but it does help me
> understand language constructs. I have seen statements like
>
 data C3 c3 a  => Address c3 a = Address c3 a
>

Incidentally, there seems to be a consensus that this a Bad Idea [1].
Even when you specify a type class context on a data declaration,
Haskell still requires you to specify the context on functions that
use that data (Address c a).  What's worse is that you need the class
restriction for *all* functions that use an Address, even if they
don't operate on the component parts and don't make use of the type
class at all.  Basically, it ends up making all your type signatures
longer with no benefit.

If you really want to ensure that every "Address c a" has this
context, then use a smart constructor:

address :: C3 c3 a => c3 -> a -> Address c3 a
address = Address

and don't export the Address data constructor.

Also, Andrew said that type classes are closer to Java interfaces than
C++ objects.  This is true, but you may find the difference useful
too.  A small example of a common OOP-er mistake should demonstrate:

-- return a Float if True, else an Int.  At least it would if type
classes were interfaces.
toFloat :: Num a => Int -> Bool -> a
toFloat x True = (fromIntegral x) :: Float
toFloat x False = x

OOP-style interfaces have two features: they specify methods that are
available for all types which implement the interface, and they are an
existentially-quantified data constructor.  Equivalent code in Java
would return an existentially-quantified type - we know the interface
methods are supported but not the data type, so the interface methods
are all we can do.  The exact type (either Float or Int) is wrapped in
this existentially quantified box.

Haskell type classes don't do existential quantification, which is why
the above doesn't compile.  The return value of this function must be
any a with a Num instance, and the caller (not toFloat) gets to choose
the exact type to instantiate.

Translating an interface to Haskell requires that you write both parts:

class Num a where ...

data INum = forall a. Num a => INum a
--requires the ExistentialQuantification extension

-- now toFloat works
toFloat :: Int -> Bool -> INum
toFloat x True = INum ((fromIntegral x) :: Float)
toFloat x False = INum x

Now the type variable is stuck in the INum type instead of being
universally quantified (top-level forall), which is what an interface
does.

I think most Haskellers would prefer to choose a design that doesn't
require existential quantification, but it really depends on the
problem.

John

[1] GHC sources refer to this context as "stupid theta", see further
discussion at 
http://hackage.haskell.org/trac/haskell-prime/wiki/NoDatatypeContexts
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Actors and message-passing a la Erlang

2010-07-25 Thread Bernie Pope
On 26 July 2010 06:55, Yves Parès  wrote:
> I've been studying Erlang and Scala, and I was wondering if someone has
> already implemented an actors and message passing framework for concurrent
> and distributed programs in Haskell.

I've recently been working on MPI bindings for Haskell:

   http://github.com/bjpop/bindings-mpi

They are incomplete, but usable.

Cheers,
Bernie.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] hGetContents: resource exhausted

2010-07-25 Thread Lally Singh
Hey all,

  This is on OpenSolaris.  Simple attempts to build cabal packages
give me this error, and I don't know what it means.  Here's an
example:
[07/25 18:51::la...@sol type-level]$ runghc Setup.hs configure
Configuring type-level-0.2.4...
Setup.hs: fd:8: hGetContents: resource exhausted (Resource temporarily
unavailable)
Setup.hs: fd:8: resource exhausted

Does anyone know what this means?  I'm trying to just get the llvm
bindings installed (requiring mtl & type-level).

Cheers,
-Lally
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Tiger compiler in Haskell: annotating abstract syntax tree

2010-07-25 Thread John Meacham
On Mon, Jul 19, 2010 at 01:51:52PM -0300, José Romildo Malaquias wrote:
>   data Exp
> = IntExp Integer
> | VarExp Symbol
> | AssignExp Symbol Exp
> | IfExp Exp Exp (Maybe Exp)
> | CallExp Symbol [Exp]
> | LetExp [Dec] Exp
>
>   data Dec
>  = TypeDec Symbol Ty
>  | FunctionDec Symbol [(Symbol,Symbol)] (Mybe Symbol) Exp
>  | VarDec Symbol (Maybe Symbol) Exp
>
> Expressions can have type annotations, but declarations can not.

Hi, my favorite solution to this is using two level types. They don't
only allow annotating the AST with information, but also allow things
like generic unification over terms or hash consing for trivial CSE. As
an example, you would translate. your thing to

>   data Exp e
> = IntExp Integer
> | VarExp Symbol
> | AssignExp Symbol e
> | IfExp Exp Exp (Maybe e)
> | CallExp Symbol [e]
> | LetExp [Dec e] e
>
>   data Dec e
>  = TypeDec Symbol Ty
>  | FunctionDec Symbol [(Symbol,Symbol)] (Maybe Symbol) e
>  | VarDec Symbol (Maybe Symbol) e

we simply replace the recursive argument 'Exp' with a type parameter. 

Now, to create an unannotated version of the AST

> newtype Fix e = F (e (Fix e))
> type SExp = Fix Exp

now if you want to annotate each node with something,

> data FixAnnotated a e = FA a (e (FixAnnotated a e))
> type ExpTy = TypeAnnotated Ty Exp

but you can do much more interesting things, imagine you want to do
common subexpression elimination on your whole program, using a hash
table of subterms to identify when the same thing is calculated more
than once. You could do something like

> newtype FixHash e = FixHash (e Int)

notice our recursive parameter is just an 'Int' this will be the index
into the table of the given subexpresion. You can write a wholely geneic
CSE pass that does not even know about the structure of your terms!

for more advanced things like a fully generic unification, see the
following paper. In addition to the two-level types trick, the paper
talks about parameterized classes, though I wouldn't recommend them so
much, a useful trick sure, but not really essential for this task. the
two level type stuff is golden though.

unify:
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.20.8205

I have attached a utility module I use for two level types, feel free to
modify it for your needs.

John


--
John Meacham - ⑆repetae.net⑆john⑈ - http://notanumber.net/

{-# OPTIONS_GHC -XMultiParamTypeClasses -XFlexibleContexts 
-XUndecidableInstances #-}
module Fix where

import Control.Applicative
import Control.Monad
import Data.Monoid
import qualified Data.Foldable as F
import qualified Data.Traversable as F


-- The basic 'Fix' type, It creates a simple recursive type.

newtype Fix f = F (f (Fix f))

instance Show (f (Fix f)) => Show (Fix f) where
showsPrec n (F x) = showsPrec n x

instance Eq (f (Fix f)) => Eq (Fix f) where
F x == F y = x == y

instance Ord (f (Fix f)) => Ord (Fix f) where
F x `compare` F y = x `compare` y

foldFix :: Functor f => (f w -> w) -> Fix f -> w
foldFix f (F ji) =  f (fmap (foldFix f) ji)

foldFixM :: (Monad m,F.Traversable f) => (f w -> m w) -> Fix f -> m w
foldFixM f (F ji) =  f =<< (F.mapM (foldFixM f) ji)

foldFixM' :: (Monad m,F.Traversable f) => (Fix f -> m (Fix f)) -> (f w -> m w) 
-> Fix f -> m w
foldFixM' fd f x = do
F x <- fd x
f =<< (F.mapM (foldFixM' fd f) x)

-- A recursive type that attaches some memoized data to each subterm

data FixM f a = FM a (f (FixM f a))

instance Functor f => Functor (FixM f) where
fmap f (FM x y) = FM (f x) (fmap (fmap f) y)

instance F.Foldable f => F.Foldable (FixM f) where
foldMap f (FM x y) = f x `mappend` F.foldMap (F.foldMap f) y

instance (Functor f, F.Traversable f) => F.Traversable (FixM f) where
traverse f (FM x y) = FM <$> f x <*> (F.traverse (F.traverse f) y)

--instance Eq (f (FixM f a)) => Eq (FixM f a) where
--FM _ x == FM _ y = x == y

--instance Ord (f (FixM f a)) => Ord (FixM f a) where
--FM _ x `compare` FM _ y = x `compare` y

fixMemo :: FixM f a -> a
fixMemo (FM a _) = a

fromFixMemo :: FixM f a -> (a,f (FixM f a))
fromFixMemo (FM a x) = (a,x)

toFixMemo ::  (f (FixM f a) -> a) -> f (FixM f a) -> FixM f a
toFixMemo f x = FM (f x) x


fixDeMemoize :: Functor f => FixM f a -> Fix f
fixDeMemoize ja = f ja where
f (FM _ j) = F (fmap f j)


fixMemoize :: Functor f => (f (FixM f a) -> a) -> Fix f -> FixM f a
fixMemoize f (F ji) =  foldFix f' (F ji) where
f' x = FM (f x) x

-- relys on laziness
fixMemoizeKnot :: Functor f => (c -> f (FixM f a) -> (c,a)) -> c -> Fix f -> 
FixM f a
fixMemoizeKnot f c fji = g c fji where
g c (F ji) = FM a nji where
(c',a) = f c nji
nji = fmap (g c') ji

fixMemoizeM :: (Monad m,F.Traversable f) => (f (FixM f a) -> m a) -> Fix f -> m 
(FixM f a)
fixMemoizeM f (F ji) =  foldFixM f' (F ji) where
f' x = do fx <- f x; return $ FM fx x

-- like fixMemoize, but lets you examine nodes on the way down as well

Re: [Haskell-cafe] Actors and message-passing a la Erlang

2010-07-25 Thread Stephen Tetley
Volker Stolz and Frank Huch implemented Erlang style
distribution/concurrency for Haskell quite a while ago - a search
should turn up the relevant papers, the code might have disappeared.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread Edward Z. Yang
Excerpts from aditya siram's message of Sun Jul 25 17:13:16 -0400 2010:
> Eta-reducing is nice, and sometimes it makes code more readable. But 'flip'
> is one of those functions that always seems to hinder rather than help
> readability, conversely factoring out flip always makes code easier to
> comprehend. I don't see a need for its existence - maybe I'm missing
> something and more experienced Haskellers can comment.

An interesting alternate spin on flip is infix notation combined with partial
application, such as:

(`foobar` 3)

which is equivalent to

\x -> foobar x 3

I frequently use this, although the jury's out on whether or not it's more 
readable.

Cheers,
Edward
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] How to do this with associated types?

2010-07-25 Thread Christopher Lane Hinson




But what to do with Maybe?


instance Result Maybe where
  type Failure Maybe = forall e. e -- can't do this
  failure _ = Nothing
  success x = Just x


Normally, I would use: type Failure Maybe = ()

Unless the ability to discard information of any type is somehow a salient 
feature.

Friendly,
--L

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread Daniel Fischer
On Sunday 25 July 2010 23:13:16, aditya siram wrote:
> Eta-reducing is nice, and sometimes it makes code more readable. But
> 'flip' is one of those functions that always seems to hinder rather than
> help readability, conversely factoring out flip always makes code easier
> to comprehend. I don't see a need for its existence - maybe I'm missing
> something and more experienced Haskellers can comment.
>
> -deech

For example,

sortBy (flip compare)

is very convenient (easier to parse¹ and it provides fewer opportunities 
for error than (\a b -> compare b a)).
Also

foldl' (flip Set.insert) Set.empty values

and such stuff.

Sometimes, functions have the wrong argument order for what you want to do, 
then flip is very handy.

¹ This is of course not a universal truth but a personal preference.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread Antoine Latter
On Sun, Jul 25, 2010 at 4:13 PM, aditya siram  wrote:
> Eta-reducing is nice, and sometimes it makes code more readable. But 'flip'
> is one of those functions that always seems to hinder rather than help
> readability, conversely factoring out flip always makes code easier to
> comprehend. I don't see a need for its existence - maybe I'm missing
> something and more experienced Haskellers can comment.
>

I'm a fan of (flip map), (flip mapM) and the like. These are usually
renamed 'for' and 'forM' (and then 'forM_', of course).

It makes for nice in-line function literals:

> flip map xs $ \elem ->
>do something long and complex
>with xs

Antoine
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Is 'flip' really necessary?

2010-07-25 Thread aditya siram
Eta-reducing is nice, and sometimes it makes code more readable. But 'flip'
is one of those functions that always seems to hinder rather than help
readability, conversely factoring out flip always makes code easier to
comprehend. I don't see a need for its existence - maybe I'm missing
something and more experienced Haskellers can comment.

-deech
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Actors and message-passing a la Erlang

2010-07-25 Thread Yves Parès
Hello !

I've been studying Erlang and Scala, and I was wondering if someone has
already implemented an actors and message passing framework for concurrent
and distributed programs in Haskell.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] How to do this with associated types?

2010-07-25 Thread Alexey Karakulov
Suppose I have one piece of code like this:

> class Result r e | r -> e where
>    failure :: e -> r a
>    success :: a -> r a

> at :: Result r String => [a] -> Int -> r a
> at xs i = if i >= 0 && i < length xs
>     then success (xs !! i)
>     else failure "Wrong index"

Either instance of Result is quite straightforward:

> instance Result (Either e) e where
>     failure e = Left e
>     success x = Right x

Maybe instance is discarding failure information:

> instance Result Maybe e where
>     failure _ = Nothing
>     success x = Just x

Some tests it in ghci:

ghci> let xs = [0,1,2]
ghci> at xs 2 :: Either String Integer
Right 2
ghci> at xs 3 :: Either String Integer
Left "Wrong index"
ghci> at xs 2 :: Maybe Integer
Just 2
ghci> at xs 3 :: Maybe Integer
Nothing

I'd like to replace functional dependencies with type families
(associated types in my case):

> class Result r where
>   type Failure
>   failure :: Failure r -> r a
>   success :: a -> r a

Either instance is ok:

> instance Result (Either e) where
>   type Failure (Either e) = e
>   failure e = Left e
>   success x = Right x

But what to do with Maybe?

> instance Result Maybe where
>   type Failure Maybe = forall e. e -- can't do this
>   failure _ = Nothing
>   success x = Just x
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Random this! ;-)

2010-07-25 Thread michael rice
Cool. Everything's there but the N.

Learning Haskell is a lot like learning to dance.

Michael


--- On Sun, 7/25/10, Ozgur Akgun  wrote:

From: Ozgur Akgun 
Subject: Re: [Haskell-cafe] Random this! ;-)
To: "Max Rabkin" 
Cc: "michael rice" , haskell-cafe@haskell.org
Date: Sunday, July 25, 2010, 3:17 PM

Sorry but I'll just go ahead and eta reduce it :)

rollNDiceIO = flip replicateM $ randomRIO (1,6)

On 25 July 2010 16:44, Max Rabkin  wrote:

On Sun, Jul 25, 2010 at 5:39 PM, michael rice  wrote:


>

> I know, ugly, but at least I got it to work. What's a better way to generate 
> this list?



rollNDiceIO n

   = sequence . replicate n $ randomRIO (1,6)

{{ sequence . replicate n = replicateM n }}

   = replicateM n $ randomRIO (1, 6)



--Max

___

Haskell-Cafe mailing list

Haskell-Cafe@haskell.org

http://www.haskell.org/mailman/listinfo/haskell-cafe




-- 
Ozgur Akgun




  ___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Random this! ;-)

2010-07-25 Thread Ozgur Akgun
Sorry but I'll just go ahead and eta reduce it :)

rollNDiceIO = flip replicateM $ randomRIO (1,6)

On 25 July 2010 16:44, Max Rabkin  wrote:

> On Sun, Jul 25, 2010 at 5:39 PM, michael rice  wrote:
> >
> > I know, ugly, but at least I got it to work. What's a better way to
> generate this list?
>
> rollNDiceIO n
>   = sequence . replicate n $ randomRIO (1,6)
> {{ sequence . replicate n = replicateM n }}
>   = replicateM n $ randomRIO (1, 6)
>
> --Max
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
Ozgur Akgun
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Yet another monad transformer or silly usage of Either?

2010-07-25 Thread David Menendez
2010/7/25 Eugeny N Dzhurinsky :
> Hello, everybody!
>
> I am trying to develop some sort of library, which supposed to sign into a WEB
> service, then perform some requests with it.
>
> Initially I designed methods in the following way
>
> data DServError = InvalidCredentials | InvalidRequest | ...
>
> newtype Result a = Result { getOpResult :: Either DServError a }
>
> data DSession = Session { ... }
>
> data DLoginResponse = LoginResponse { currentSession :: DSession, ... }
>
> login :: String -> String -> IO ( Result LoginResponse )
>
> servRequest1 :: DSession -> ParamType1 -> ParamType2 -> ... -> IO ( Result 
> DServResponse )
>
>
> Now I want to be able of doing something like
>
> authenticatedReq = do
>    loginResponse <- login "username" "password"
>    let session = currentSession loginResponse
>    servRequest1 session ... ... ...
>    servRequest2 session ... ... ...
>    ...
>
> so if login succeeds - I will be able to extract Right data from the Either 
> response ( with
> explicit or implicit usage of getOpResult), if any of operations within "do"
> block will fail with DServError - then an error should be reported.
>
> I think the solution for this may be using Control.Exception and it's
> try/catch?

That would work. If all of your operations require IO, you may as well
use IO for exceptions. It really depends on how explicit you want to
be about the varieties of exceptions your code may throw.

The documentation for Control.Exception has a pretty good explanation
of how to define instances for Exception.

e.g.,

data DServError = InvalidCredentials | ... deriving (Show, Typeable)

instance Exception DServError DServError

login :: String -> String -> IO LoginResponse
servRequest1 :: DSession -> ParamType1 -> ... -> IO DServResponse


It may be a better choice to make each exception its own type, and
possibly create a sub-heirarchy. E.g.,

data DServError = forall a. (Exception a) => DServError a deriving (Typeable)

instance Show DServError where show (DServError a) = show a

dServErrorToException :: Exception a => a -> SomeException
dServErrorToException = toException . DServError

dServErrorFromException :: Exception a => SomeException -> Maybe a
dServErrorFromException x = fromException x >>= \(DServError a) -> cast a

data InvalidCredentials deriving (Show, Typeable)

instance Exeption InvalidCredentials where
toException = dServErrorToException
fromException = dServErrorFromException

data InvalidRequest deriving (Show, Typeable)

instance Exeption InvalidRequest where
toException = dServErrorToException
fromException = dServErrorFromException

etc.

This allows you to write "m `catch` \(e :: DServError) -> ..." and "m
`catch` \InvalidCredentials -> ..." without worrying about
pattern-match errors.

-- 
Dave Menendez 

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Yet another monad transformer or silly usage of Either?

2010-07-25 Thread Job Vranish
Yeah, ErrorT should do what you want (EitherT is probably essentially the
same thing)

login would have the type:
login :: String -> String -> ErrorT DServError IO LoginResponse

and you would use it like this:
result <- runErrorT $ authenticatedReq

You can use runErrorT, or catch when you want to process a possible error.

result would have the type Either DServError whatever. This would leave out
the Result type, but if you really want to, you can add it with the
appropriate lifting.

Hope that helps,

- Job


2010/7/25 Eugeny N Dzhurinsky 

> Hello, everybody!
>
> I am trying to develop some sort of library, which supposed to sign into a
> WEB
> service, then perform some requests with it.
>
> Initially I designed methods in the following way
>
> data DServError = InvalidCredentials | InvalidRequest | ...
>
> newtype Result a = Result { getOpResult :: Either DServError a }
>
> data DSession = Session { ... }
>
> data DLoginResponse = LoginResponse { currentSession :: DSession, ... }
>
> login :: String -> String -> IO ( Result LoginResponse )
>
> servRequest1 :: DSession -> ParamType1 -> ParamType2 -> ... -> IO ( Result
> DServResponse )
>
>
> Now I want to be able of doing something like
>
> authenticatedReq = do
>loginResponse <- login "username" "password"
>let session = currentSession loginResponse
>servRequest1 session ... ... ...
>servRequest2 session ... ... ...
>...
>
> so if login succeeds - I will be able to extract Right data from the Either
> response ( with
> explicit or implicit usage of getOpResult), if any of operations within
> "do"
> block will fail with DServError - then an error should be reported.
>
> I think the solution for this may be using Control.Exception and it's
> try/catch? Or may be there's some trick available for Either?
>
> I looked at EitherT, and it seems that I have to wrap every invocation into
> EitherT and then chain them with >>/>>=
>
> --
> Eugene Dzhurinsky
>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Andrew Coppin

Vo Minh Thu wrote:

2010/7/25 Andrew Coppin :
  

Since you're interested in comparisons... A method is simply a way of giving
the same name to several different functions, and have the compiler pick the
correct one based on the argument types.
[snip]



Actually in Haskell, the choice of the correct definition is not only
based on the argument types. It could be based on the result type:
  


Yes, quite right.

It's also possible to use "phantom types" to make the program do 
different things even thought the run-time representation of data hasn't 
changed at all. Haskell is like that. ;-)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Random this! ;-)

2010-07-25 Thread michael rice
Hi Max,

Wow!

I tried both *sequence* and *replicate* but guess I didn't put them together 
properly. I didn't even know there was a *replicateM*.

Much cleaner.

Thanks

Michael

--- On Sun, 7/25/10, Max Rabkin  wrote:

From: Max Rabkin 
Subject: Re: [Haskell-cafe] Random this! ;-)
To: "michael rice" 
Cc: haskell-cafe@haskell.org
Date: Sunday, July 25, 2010, 11:44 AM

On Sun, Jul 25, 2010 at 5:39 PM, michael rice  wrote:
>
> I know, ugly, but at least I got it to work. What's a better way to generate 
> this list?

rollNDiceIO n
   = sequence . replicate n $ randomRIO (1,6)
{{ sequence . replicate n = replicateM n }}
   = replicateM n $ randomRIO (1, 6)

--Max



  ___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Random this! ;-)

2010-07-25 Thread Tobias Brandt
Look for the function replicateM in the module Control.Monad.

On 25 July 2010 17:39, michael rice  wrote:

> Hi All,
>
> From: http://en.wikibooks.org/wiki/Haskell/Understanding_monads/State
>
>Exercises
>
>1. Implement a function rollNDiceIO :: Int -> IO [Int] that,
>   given an integer, returns a list with that number of pseudo-
>   random integers between 1 and 6.
>
>
> After a lot of learning what not to do, this is the best I could come up
> with.
>
> rollNDiceIO :: Int -> IO [Int]
> rollNDiceIO n = mapM (\x -> randomRIO(1,6)) (replicate n 1)
>
> I know, ugly, but at least I got it to work. What's a better way to
> generate this list?
>
> Michael
>
>
>
> ___
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Random this! ;-)

2010-07-25 Thread Max Rabkin
On Sun, Jul 25, 2010 at 5:39 PM, michael rice  wrote:
>
> I know, ugly, but at least I got it to work. What's a better way to generate 
> this list?

rollNDiceIO n
   = sequence . replicate n $ randomRIO (1,6)
{{ sequence . replicate n = replicateM n }}
   = replicateM n $ randomRIO (1, 6)

--Max
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Random this! ;-)

2010-07-25 Thread michael rice
Hi All,

From: http://en.wikibooks.org/wiki/Haskell/Understanding_monads/State

   Exercises

   1. Implement a function rollNDiceIO :: Int -> IO [Int] that,
  given an integer, returns a list with that number of pseudo-
  random integers between 1 and 6.


After a lot of learning what not to do, this is the best I could come up with.

rollNDiceIO :: Int -> IO [Int]
rollNDiceIO n = mapM (\x -> randomRIO(1,6)) (replicate n 1)

I know, ugly, but at least I got it to work. What's a better way to generate 
this list?

Michael




  ___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Yet another monad transformer or silly usage of Either?

2010-07-25 Thread Eugeny N Dzhurinsky
Hello, everybody!

I am trying to develop some sort of library, which supposed to sign into a WEB
service, then perform some requests with it.

Initially I designed methods in the following way

data DServError = InvalidCredentials | InvalidRequest | ...

newtype Result a = Result { getOpResult :: Either DServError a }

data DSession = Session { ... }

data DLoginResponse = LoginResponse { currentSession :: DSession, ... }

login :: String -> String -> IO ( Result LoginResponse )

servRequest1 :: DSession -> ParamType1 -> ParamType2 -> ... -> IO ( Result 
DServResponse )


Now I want to be able of doing something like

authenticatedReq = do
loginResponse <- login "username" "password"
let session = currentSession loginResponse
servRequest1 session ... ... ...
servRequest2 session ... ... ...
...

so if login succeeds - I will be able to extract Right data from the Either 
response ( with 
explicit or implicit usage of getOpResult), if any of operations within "do"
block will fail with DServError - then an error should be reported.

I think the solution for this may be using Control.Exception and it's
try/catch? Or may be there's some trick available for Either?

I looked at EitherT, and it seems that I have to wrap every invocation into
EitherT and then chain them with >>/>>=

-- 
Eugene Dzhurinsky


pgpP8eCkSjmYB.pgp
Description: PGP signature
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Vo Minh Thu
2010/7/25 Andrew Coppin :
> Patrick Browne wrote:
>>
>> Andrew,
>> Thanks for your detailed feedback, it is a great help.
>>
>
> Well, I like to be helpful.
>
>> I appreciate that the code does not do anything useful, nor is it an
>> appropriate way to write Haskell, but it does help me
>> understand language constructs.
>
> Personally, I find it easier to understand things when they do something
> meaningful, but sure.
>
>> I am studying the Haskell type class system as part of a language
>> comparison. I am trying to exercise and understand the constructs rather
>> than develop a meaningful application.
>>
>
> The best way to understand Haskell is... to completely forget everything you
> already know, and start again from scratch. ;-) Still, I gather that's not
> the point of this particular exercise.
>
> Since you're interested in comparisons... A method is simply a way of giving
> the same name to several different functions, and have the compiler pick the
> correct one based on the argument types.
> [snip]

Actually in Haskell, the choice of the correct definition is not only
based on the argument types. It could be based on the result type:

class C a where
  f :: a
  g :: a -> Int
  h :: String -> a

An example of the 'h' case is simply the 'read' function:

Prelude> :t read
read :: (Read a) => String -> a

For instance:

Prelude> read "1" :: Int
1
Prelude> read "1" :: Double
1.0

Note that usually, the type annotation is not needed because the
compiler has enough information from the context to infer it.

Cheers,
Thu
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Andrew Coppin

Patrick Browne wrote:

Andrew,
Thanks for your detailed feedback, it is a great help.
  


Well, I like to be helpful.


I appreciate that the code does not do anything useful, nor is it an
appropriate way to write Haskell, but it does help me
understand language constructs.


Personally, I find it easier to understand things when they do something 
meaningful, but sure.



I am studying the Haskell type class system as part of a language
comparison. I am trying to exercise and understand the constructs rather
than develop a meaningful application.
  


The best way to understand Haskell is... to completely forget everything 
you already know, and start again from scratch. ;-) Still, I gather 
that's not the point of this particular exercise.


Since you're interested in comparisons... A method is simply a way of 
giving the same name to several different functions, and have the 
compiler pick the correct one based on the argument types. That's what 
methods do in OOP, and it's what they do in Haskell too. The notable 
difference is that in Haskell, all types are known at compile-time. 
(Unless you turn on certain extra non-standard language features...)


The other point worth realising is that since Haskell has first-class 
functions, you don't "need" classes quite so much. (E.g., Java has the 
Runnable interface so that the JVM can call an object's run() method. In 
Haskell, you just say forkIO and pass it the function to execute. 
Similar deal for GUI callbacks and so forth.)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re[Haskell-cafe] ad large file and match lines to a pattern

2010-07-25 Thread grzyb

Hi,

I'm a beginner in haskell, I was trying to write the following code, but I
still encourage some problems, can you help me with that?

I need to read a large file and try to match each line to a pattern which is
int,int value="string"
for example:
0,1 value="string1"
1,5 value="string2"
when the line matches the pattern then I need to get those 3 values (int,
int, string) and pass them to my function.


-- 
View this message in context: 
http://old.nabble.com/Read-large-file-and-match-lines-to-a-pattern-tp29260322p29260322.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Patrick Browne
Andrew,
Thanks for your detailed feedback, it is a great help.
I appreciate that the code does not do anything useful, nor is it an
appropriate way to write Haskell, but it does help me
understand language constructs. I have seen statements like

>>> data C3 c3 a  => Address c3 a = Address c3 a


and wondered what they mean and how could they be used.

I am studying the Haskell type class system as part of a language
comparison. I am trying to exercise and understand the constructs rather
than develop a meaningful application.

Perhaps I should have mentioned this in my post.

Thanks again,
Pat


This message has been scanned for content and viruses by the DIT Information 
Services E-Mail Scanning Service, and is believed to be clean. http://www.dit.ie
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] default function definitions

2010-07-25 Thread Malcolm Wallace
-- Is it true that instances must exists before we can run function  
or

make subclasses?
instance C1  Person where
instance C1  Employee where


You can *call* class methods only for types which are instances of  
that

class.


But you can certain *write* functions that make use of the class  
methods, even if no instances exist, provided they remain polymorphic  
over the class. e.g.


cumulativeAges :: C1 a => [a] -> Integer
cumulativeAges = sum . map age

The assumption would be that some client of your code would eventually  
need to declare at least one instance, for some type they are  
interested in, before they could use the function at that concrete  
type.  Those instances need not be in the same module as the  
definition of the class, nor in the same module as function  
definitions like cumulativeAges.



Regards,
Malcolm

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Stephen Tetley
On 25 July 2010 13:09, Andrew Coppin  wrote:

> This is not valid in Haskell '98. This is actually a type system extension
> known as "multi-parameter type classes", which do not even vaguely
> correspond to anything in normal OOP. (Except for being very slightly
> similar to generics, perhaps.)


Closest perhaps to multimethods in Cecil and and I think CLOS - though
multimethods in CLOS does seem to take things far out into space with
:before :after and :around.
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe



Re: [Haskell-cafe] Type problems

2010-07-25 Thread Daniel Fischer
On Sunday 25 July 2010 14:47:41, Andrew Coppin wrote:
> Daniel Fischer wrote:
> > On Sunday 25 July 2010 14:12:03, Andrew Coppin wrote:
> >> Isn't there a "default" declaration where you can specify type
> >> defaulting?
> >
> > Yes, you can have one default declaration per module.
>
> Not a feature I ever use. I just vaguely remembered reading about it
> somewhere... (No idea if it has any effect on GHCi though.)
>

ghci ignores default declarations (but has extended defaulting rules), so 
at the ghci prompt, you always get Integer for a generic Num type.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Type problems

2010-07-25 Thread Andrew Coppin

Daniel Fischer wrote:

On Sunday 25 July 2010 14:12:03, Andrew Coppin wrote:
  

Isn't there a "default" declaration where you can specify type
defaulting?



Yes, you can have one default declaration per module.
  


Not a feature I ever use. I just vaguely remembered reading about it 
somewhere... (No idea if it has any effect on GHCi though.)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Type problems

2010-07-25 Thread Daniel Fischer
On Sunday 25 July 2010 14:12:03, Andrew Coppin wrote:
> Ivan Miljenovic wrote:
> > On 25 July 2010 05:50, Tobias Brandt  wrote:
> >> You have to fix the type of 1 and 6, e.g. by writing
> >> x <- randomRIO (1, 6) :: IO Int
> >> or
> >> x <- randomRIO (1, 6 :: Int)
> >>  GHCi defaults integral numbers to Int, that's why it works there.
> >
> > The default numeric type is Integer, not Int.
>
> Isn't there a "default" declaration where you can specify type
> defaulting?

Yes, you can have one default declaration per module.

The default default is (Integer, Double), meaning Integer is chosen if it's 
possible, otherwise Double is tried (for Fractional, Floating, ... 
constraints), if that doesn't satisfy all constraints either, error out 
with Ambiguous type variable ...

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Type problems

2010-07-25 Thread Andrew Coppin

Ivan Miljenovic wrote:

On 25 July 2010 05:50, Tobias Brandt  wrote:
  

You have to fix the type of 1 and 6, e.g. by writing
x <- randomRIO (1, 6) :: IO Int
or
x <- randomRIO (1, 6 :: Int)
 GHCi defaults integral numbers to Int, that's why it works there.



The default numeric type is Integer, not Int.
  


Isn't there a "default" declaration where you can specify type defaulting?

At least, "default" appears to be a Haskell language keyword - much to 
my irritating the other day... ;-)


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] data type declaration

2010-07-25 Thread Andrew Coppin

Patrick Browne wrote:

Hi,
I am trying to understand the data type declaration below.
What is the relation between class C3 and the data type Address below?
Where is such a technique used?
  


OK, let's see what we can come up with...


module A where
data Person = Person String Integer deriving Show
data Employee  = Employee String Integer deriving Show
  


Person and Employee are identical types, just with different names.


class C1 c1 where
  age :: c1 -> Integer
  


The "age" function works for any type declared to be an instance of C1.


instance C1  Person where
   age(Person "P1" 1) = 1


instance C1  Employee where
age(Employee "E1" 1) = 1
  


Person and Employee are both declared to be instances of C1.

Incidentally, those declarations look *very* dubious. What the first one 
says, for example, is that if a person is called "P1" and their age is 
1, then return 1. If the name is not "P1" or the age is not 1, crash.



class C1 c2 =>  C2 c2 where
  name :: c2 -> String
  


The "name" function works for any type declared to be an instance of C2. 
Any such type must also be an instance of C1.



instance C2  Person where
  name(Person "P2" 1) = "P2"

instance C2  Employee where
name(Employee "E2" 1) = "E2"
  


Person and Employee are both instances of C2 (which is allowed, since 
they are already instances of C1).


Again, the instance declarations look highly dubious.


class C2 c3 =>  C3 c3 a where
  address :: c3  -> a
  


This is not valid in Haskell '98. This is actually a type system 
extension known as "multi-parameter type classes", which do not even 
vaguely correspond to anything in normal OOP. (Except for being very 
slightly similar to generics, perhaps.)


Here C3 is a relation *between* two types (type "c3" and type "a"). For 
any so-related types, the "address" fucntion can map one type to the 
other. (Presumably by returning the contents of an address field...) 
This is a very odd way to define such an action.



instance C3 Person String where
  


The types Person and String are related by C3 as described above. 
However, calling "address" will crash immediately (since no 
implementation is supplied).



-- ** What are the semantics or purpose of this construct.
-- ** Is the type declared in the context of a class.
data C3 c3 a  => Address c3 a = Address c3 a
  


This defines a new type named "Address". The type has two type 
parameters ("c3" and "a"), and a value of this type has two fields.


In other words, if you say "Address Rock Stone", then an Address value 
has two fields, the first one of type Rock, the second of type Stone.


Also, the type parameters are required to be related by C3. So unless 
you write "instance C3 Rock Stone", you cannot say "Address Rock Stone". 
It would be a type error. However, since "instance C3 Person String" 
exists above, you may say "Address Person String".



instance C3 Person (Address String String) where
  


This says that the type "Person" and the type "Address String String" 
are related by C3 as well - which is amusing, given that "Address String 
String" is a type error due to the fact that we don't have "instance C3 
String String"...


In short, this big tangle of code shouldn't even compile, and if it 
does, I have no clue what in the name of God it actually does. It 
appears to have been written by somebody who has no idea what they're doing.


If you want to know what a specific language construct does, or why 
you'd use it, or which way you'd attack a specific problem, I (and 
everybody else here) can try to offer some explanation. But the code 
you're showing me doesn't really make any sense.


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe