Roman Cheplyaka | 18 May 2013 18:25
Gravatar

Non-deterministic behaviour of aeson's parser

I am observing a non-deterministic behaviour of aeson's parser.

I'm writing here in addition to filing a bug report [1] to draw
attention to this (pretty scary) problem.

To try to reproduce this problem, do this:

  git clone https://gist.github.com/5604887.git aeson
  cd aeson
  ghc aeson.hs
  ./aeson | sort | uniq -c

This is my result:

    32 Left "key \"module\" not present"
    55 Left "When parsing the record SymValue of type Main.SymValueInfo the key fixity was not present."
  1913 Right ()

Can others reproduce this in their environments?

Does anyone have ideas about where the bug may lie?
Many aeson's dependencies do unsafe IO stuff that could lead to
such consequences.

Roman

[1]: https://github.com/bos/aeson/issues/125
mukesh tiwari | 18 May 2013 13:07
Picon
Gravatar

Compiler error in Parsec using ByteString

Hello all,
I am trying to write a small calculator using Parsec. Every thing went fine and I wrote this [1] and now I am trying to use ByteString to make it more faster but getting compiler error which I am not able to figure out. Could some one please tell me what is wrong with this code. In case of indentation error, code on hpaste[2]

{-# LANGUAGE OverloadedStrings #-}
import qualified Text.Parsec.Token as Token
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.Expr
import Text.Parsec.Combinator
import Text.Parsec.Language
import qualified Text.Parsec.ByteString.Lazy as T
import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Applicative hiding ( ( <|> ) , many )
import Data.Maybe ( fromJust )

languageDef = emptyDef { Token.commentStart   = "/*"
               , Token.commentEnd     = "*/"
               , Token.commentLine    = "//"
               , Token.nestedComments = False
               , Token.identStart     = letter <|> char '_'
               , Token.identLetter    = alphaNum <|> oneOf "_'"
               , Token.opStart        = Token.opLetter emptyDef
               , Token.opLetter       = oneOf ":!#$%&*+./<=>? <at> \\^|-~"
               , Token.reservedOpNames= ["*" , "/" , "^" , "+" , "-" ]
               , Token.reservedNames  = []
               , Token.caseSensitive  = True
               }

lexer = Token.makeTokenParser languageDef

identifier = Token.identifier lexer
reserved = Token.reserved lexer
operator = Token.operator lexer
reservedOp = Token.reservedOp lexer
natural = Token.natural lexer
integer = Token.integer lexer
float = Token.float lexer
lexeme = Token.lexeme lexer
parens = Token.parens lexer
whiteSpace = Token.whiteSpace lexer
semi = Token.semi lexer
comma = Token.comma lexer
colon = Token.colon lexer
dot = Token.dot lexer
semiSep = Token.semiSep lexer
commaSep = Token.commaSep lexer



data Expr = Num Integer
          | Add Expr Expr
          | Sub Expr Expr
          | Mul Expr Expr
          | Div Expr Expr
          | Exp Expr Expr
          deriving Show

exprCal    :: T.Parser Expr
exprCal    = buildExpressionParser table factor
    

table   = [ [ op "^"  Exp AssocRight ]
          , [ op "*"  Mul AssocLeft, op "/"  Div AssocLeft ]
          , [ op "+"  Add AssocLeft, op "-"  Sub AssocLeft ]
          ]         
        where
          op s f assoc  = Infix ( reservedOp s  >> return f ) assoc

factor :: T.Parser Expr
factor  = parens  exprCal
        <|> Num <$> integer
       


calExpression  :: Expr -> Integer
calExpression ( Num n ) = n
calExpression ( Add e1 e2 ) = calExpression e1 + calExpression e2
calExpression ( Sub e1 e2 ) = calExpression e1 - calExpression e2
calExpression ( Mul e1 e2 ) = calExpression e1 * calExpression e2
calExpression ( Div e1 e2 ) = div ( calExpression e1 ) ( calExpression e2 )
calExpression ( Exp e1 e2 ) =   calExpression e1  ^ ( calExpression e2 )
         
                                      
calculator :: String -> Integer
calculator expr = case parse ( whiteSpace >> exprCal ) ""  ( BS.pack expr ) of
                       Left msg -> error "failed to parse"
                       Right ( val ) -> calExpression val


*Main> :load "/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs"
[1 of 1] Compiling Main             ( /Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs, interpreted )

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:56:36:
    Couldn't match type `[Char]' with `BS.ByteString'
    Expected type: OperatorTable
                     BS.ByteString () Data.Functor.Identity.Identity Expr
      Actual type: [[Operator
                       String () Data.Functor.Identity.Identity Expr]]
    In the first argument of `buildExpressionParser', namely `table'
    In the expression: buildExpressionParser table factor
    In an equation for `exprCal':
        exprCal = buildExpressionParser table factor

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:67:11:
    Couldn't match type `[Char]' with `BS.ByteString'
    Expected type: ParsecT
                     BS.ByteString () Data.Functor.Identity.Identity Expr
      Actual type: ParsecT
                     String () Data.Functor.Identity.Identity Expr
    In the return type of a call of `parens'
    In the first argument of `(<|>)', namely `parens exprCal'
    In the expression: parens exprCal <|> Num <$> integer

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:67:19:
    Couldn't match type `BS.ByteString' with `[Char]'
    Expected type: ParsecT
                     String () Data.Functor.Identity.Identity Expr
      Actual type: T.Parser Expr
    In the first argument of `parens', namely `exprCal'
    In the first argument of `(<|>)', namely `parens exprCal'
    In the expression: parens exprCal <|> Num <$> integer

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:68:21:
    Couldn't match type `[Char]' with `BS.ByteString'
    Expected type: ParsecT
                     BS.ByteString () Data.Functor.Identity.Identity Integer
      Actual type: ParsecT
                     String () Data.Functor.Identity.Identity Integer
    In the second argument of `(<$>)', namely `integer'
    In the second argument of `(<|>)', namely `Num <$> integer'
    In the expression: parens exprCal <|> Num <$> integer

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:82:46:
    Couldn't match type `BS.ByteString' with `[Char]'
    Expected type: ParsecT
                     String () Data.Functor.Identity.Identity Expr
      Actual type: T.Parser Expr
    In the second argument of `(>>)', namely `exprCal'
    In the first argument of `parse', namely `(whiteSpace >> exprCal)'
    In the expression: parse (whiteSpace >> exprCal) "" (BS.pack expr)

/Users/mukeshtiwari/Programming/Code/Compilers/ParsecExample.hs:82:62:
    Couldn't match type `BS.ByteString' with `[Char]'
    Expected type: String
      Actual type: BS.ByteString
    In the return type of a call of `BS.pack'
    In the third argument of `parse', namely `(BS.pack expr)'
    In the expression: parse (whiteSpace >> exprCal) "" (BS.pack expr)
Failed, modules loaded: none.
Prelude>


Mukesh Tiwari

[1] http://hpaste.org/88155
[2] http://hpaste.org/88156


_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
Thomas Jaeger | 18 May 2013 10:51
Picon

Extensible Records using Implicit Parameters

Hello,

Records in Haskell are somewhat of a contentious issue and many
proposals have been put forth to address the shortcomings of the current
record system [1].  Below, I introduce a small library relying on
several GHC extensions, crucially Implicit Parameters and Constraint
Kinds, which implements an extensible record system.  While by no means
production-ready, it is remarkably close to how I think an extensible
record system should function.

Record access is very convenient (reminiscent of Pascal's with
statement), while record update is somewhat cumbersome (but could
potentially be improved using Template Haskell).

Two caveats:

* Type inference for records does not work, so type signatures have to
  be provided.

* When more than one binding for an implicit parameter is in scope, it
  is not always clear which one takes precedence.  However, I think it
  is safe to assume that if the innermost binding is a let/where
  binding, it will carry the day.  In all other cases, it is probably
  safest to rely on explicit type signatures to resolve the ambiguity.

> {-# LANGUAGE ImplicitParams #-}
> {-# LANGUAGE ConstraintKinds #-}
> {-# LANGUAGE GADTs #-}
> {-# LANGUAGE RankNTypes #-}

The record type is simply the dictionary type, which is more commonly
used to reify type class dictionaries.  Here, we use it to record a
number of implicit parameter bindings, i.e. if implicit parameters of
types `fields' are in scope, then the data constructor `Rec' will create
a dictionary from them, provided an appropriate type signature is given.

> data Record fields where
>   Rec :: fields => Record fields

The `?' operator will bring the implicit parameter bindings previously
captured by `Rec' into scope.

> infixr 1 ?
> (?) :: Record fields -> (fields => r) -> r
> Rec ? e = e

This is the complete library.  Examples follow below.
========================================================================

Type synonyms to replace the awkward syntax for implicit parameter
constraints.

> type X a = ?x::a
> type Y a = ?y::a
> type Z a = ?z::a

As a first example, construct a record with fields ?x and ?y, both of
type Int.

> xy :: Record (X Int, Y Int)
> xy = let ?x = 1; ?y = 2 in Rec

To access the fields of the record, we can use the `?' operator.
Expressions involving any of the fields can appear to the right of the
operator.
* xy ? ?x ==> 1
* xy ? ?x + ?y ==> 3

The next example illustrates record update

> xy' :: Record (X Int, Y Int)
> xy' = xy ? let ?y = -2 in Rec

* xy' ? ?y ==> -2

Type signatures are required, but can be placed directly after `Rec'.

> xz = let ?x = -1; ?z = 3 in Rec :: Record (X Int, Z Int)

Record Restriction

> y :: Record (Y Int)
> y = xy ? Rec

We can combine records as follows, but the result may be implementation-
dependent if both records share fields.

> xyz, xyz' :: Record (X Int, Y Int, Z Int)
> xyz = xz ? xy ? Rec

* xyz ? ?x ==> -1

So it is probably better to disambiguate.

> xyz' = xz ? y ? Rec

* xyz' ? ?x ==> -1

========================================================================

As an application, we use records to build a rudimentary object system.

A class is a record which can access its own fields, which are supplied
as an argument.

> type Class fields = Record fields -> Record fields

Originally I tried the type 'fields => Record fields', which leads to
problems when tying the knot.

Given a class, we can get a record for property and method access by
using a fixed point combinator.

> runClass :: Class fields -> Record fields
> runClass inst = inst (runClass inst)

Type signatures for our next example.

> type N    = ?n::Int
> type AbstractFact = (?fact::Int, ?factHelper::Int -> Int -> Int)
> type ConcreteFact = (AbstractFact, N)

This is an abstract class that computes the factorial of its abstract
property `?n'.  Notice how `?n' is not included in the function's return
type.

> abstractFact :: Record ConcreteFact -> Record AbstractFact
> abstractFact r = Rec where
>   ?fact = r ? ?factHelper 1 ?n
>   ?factHelper = r ?
>     \p k -> if k == 1 then p else ?factHelper (p*k) (k-1)

It is important that `r' only be opened inside the definitions of the
methods, otherwise `runClass' will cause an infinite loop.

To go from an abstract class to a concrete class, all we need to do is
provide the missing property.

> concreteFact :: Int -> Class ConcreteFact
> concreteFact n r = abstractFact r ? let ?n = n in Rec

Quick sanity check

> testFact :: Class ConcreteFact
> testFact = concreteFact 10

* runClass testFact ? ?fact ==> 3628800

Example of overloading.

> overrideFact :: Class ConcreteFact
> overrideFact r = testFact r ? let ?fact = fact in Rec where
>   fact = r ? product [1.. ?n]

It is tempting to use the following definition
  overrideFact r = testFact r ? let ?fact = product [1.. ?n] in Rec
However, this will use `?n' from the current environment and not respond
to `?n' being overridden in a subclass.

The final example concerns multiple inheritance.  We first define a
class for computing Fibonacci numbers, similar to the one for the
factorial above.

> type Fib  = (?fib::Int, N)

> fib :: Int -> Class Fib
> fib n r = Rec where
>   ?n   = n
>   ?fib = let fibs = 0:zipWith (+) fibs (1:fibs) in r ? fibs !! ?n

A multiple-inheritance combinator

> diamond :: Class c1 -> Class c2 -> Class (c1,c2)
> diamond c1 c2 r = c1 (r ? Rec) ? c2 (r ? Rec) ? Rec

> testFactFib :: Class (ConcreteFact, Fib)
> testFactFib = diamond testFact (fib 5)

This is C++-style inheritance: We now have two copies of the field `?n'.

* runClass testFactFib ? ?fact ==> 3628800
* runClass testFactFib ? ?fib ==> 5

However, if we were to update `?n' in a subclass, both the factorial and
the Fibonacci class would both use the new value.

Alternatively, we can force the class to use a single value for `?n' by
making sure `?n' only occurs once in the list of fields, but it's
anyone's guess which value GHC will pick for `?n'.

> testFactFib' :: Class (AbstractFact, Fib)
> testFactFib' r = testFactFib (r ? Rec) ? Rec

* runClass testFactFib' ? ?fact ==> 120
* runClass testFactFib' ? ?fib ==> 5

Thomas

[1] http://hackage.haskell.org/trac/ghc/wiki/Records
TP | 17 May 2013 16:32
Picon
Favicon

question about GADT and deriving automatically a Show instance

Hi everybody,

I have a question about deriving automatically a Show instance when using 
GADT.
It works in this situation:

----------------------------
{-# LANGUAGE GADTs #-}

data Male
data Female

data Person gender where
    Dead :: Person gender
    Alive :: { name :: String
              , weight :: Float
              , father :: Person gender } -> Person gender
     deriving Show

main = do

let a = Alive "Joe" 60 Dead :: Person Male
let b = Alive "Jim" 70 a :: Person Male

print a
print b
----------------------------

Indeed:

$ runghc test_show.hs 
Alive {name = "Joe", weight = 60.0, father = Dead}
Alive {name = "Jim", weight = 70.0, father = Alive {name = "Joe", weight = 
60.0, father = Dead}}

But when I replace "father :: Person gender" by "father :: Person gender2" 
in the code (this is one of the advantages of GADT: with a classical 
algebraic data type declaration, gender2 would have to be a type variable 
for the data type), I obtain:

Can't make a derived instance of `Show (Person gender)':
      Constructor `Alive' must have a Haskell-98 type
      Possible fix: use a standalone deriving declaration instead
    In the data declaration for `Person'

So I modify my code by removing "deriving Show", and adding the line:
----------------------------
instance Show (Person gender)
----------------------------

But now, I obtain:

$ runghc test_show.hs 
GHC stack-space overflow: current limit is 536870912 bytes.
Use the `-K<size>' option to increase it.

Why (I imagine this is because there is an infinite loop in the construction 
of the show function)? Is there any workaround?

Thanks,

TP
Takayuki Muranushi | 17 May 2013 08:17
Picon
Gravatar

type-level integers for GHC

What is your recommendation for type-level integers?

I'd like to use it to improve the unittyped,
https://bitbucket.org/xnyhps/haskell-unittyped/ the library for
physical dimension. Therefore, I need negative numbers, additions, but
multiplications are not necessary.

I've been looking forward for the type-nats extension of GHC, but I
haven't been able to compile the type-nats branch. Just learned that
it still takes a few month to merge the branch into the main.
http://hackage.haskell.org/trac/ghc/wiki/Status/May13

Thijs, the original author of unittyped, has commited a branch that
uses type-nats, but I can't try that out for the same reason.

Best,
--
Takayuki MURANUSHI
The Hakubi Center for Advanced Research, Kyoto University
http://www.hakubi.kyoto-u.ac.jp/02_mem/h22/muranushi.html
Conal Elliott | 17 May 2013 01:50
Gravatar

Lambda expressions (core) to categorical form

I want to convert lambda expressions into a vocabulary of monoidal categories, so that they can be given multiple interpretations, including circuit generation and timing analysis, and hopefully some other far-out alternatives (3D visualization, animated evaluation, etc). More specifically, I want a GHC plugin that makes this transformation on GHC's Core language.

If you know of related work, have suggestions, and/or are interested in collaborating/consulting, I'd love to hear.

Thanks,

  - Conal
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
Jose A. Lopes | 16 May 2013 23:15
Picon
Favicon

List comprehensions with Word8

Hello everyone,

I was playing with Word8 and list comprehensions and
the following examples came up. I have to admit the
behavior looks quite strange because it does not seem
to be consistent. Can someone shed some light on reason
behind some of these outputs?

By the way, I have abbreviated some outputs with ellipsis ...

[1..10] :: [Word8]
[1,2,3,4,5,6,7,8,9,10]

[1..100] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,...,100]

[1..1000] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,...,232]

[1..10000] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

[1..100000] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,...,160]

[1..1000000] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,...,64]

[1..10000000] :: [Word8]
[1,2,3,4,5,6,7,8,9,10,...,128]

[1..100000000] :: [Word8]
[]

[1..1000000000] :: [Word8]
[]

Thank you,
Jose

--

-- 
José António Branquinho de Oliveira Lopes
Instituto Superior Técnico
Technical University of Lisbon
Niklas Hambüchen | 16 May 2013 17:06
Favicon
Gravatar

Infrastructure for testing the impact of a Functor/Applicative/Monad hierarchy

Reading the other thread (Adding Applicative/Functor instances to all
Monads in GHC) I was wondering if there was infrastructure for testing
what effect making the often-discussed Functor/Monad change would have:
How many packages on hackage would break etc.

I have read a few times that people have "compiled all of hackage" to
see the impact of whatever.

How do you do that?

Do you just run a loop around cabal install or have you built some more
advanced tools to visualize the results better or compile the packages
"from ground up", in order of their dependencies?

I'm interested in anything in this direction.
Daniel Díaz Casanueva | 15 May 2013 23:44
Picon
Favicon

Good to find you on LinkedIn

 
 
Minh Thu,
 
 
 
 
 
 
 
 
 
 
 
 
 
Daniel Díaz Casanueva wants to connect with you on LinkedIn.
 
 
Daniel Díaz Casanueva
Computer Software Professional View Profile »
 
 
 
 
 
 
 
 
You are receiving Invitation emails. Unsubscribe.
 
This email was intended for Minh Thu Vo (Core/Server Lead Developer at OpenERP). Learn why we included this. © 2013, LinkedIn Corporation. 2029 Stierlin Ct. Mountain View, CA 94043, USA
 
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
Patrick Browne | 15 May 2013 17:34
Picon

Propositions in Haskell

-- Hi
-- I am trying to show that a set of propositions and a conclusion the form a valid argument.
-- I used two approaches; 1) using if-then-else, 2) using pattern matching.
-- The version using if-then-else seems to be consistent with my knowledge of Haskell and logic (either of which could be wrong).
-- Can the second approach be improved to better reflect the propositions and conclusion? Maybe type level reasoning could be used?
--
-- Valid argument?
-- 1. I work hard or I play piano
-- 2. If I work hard then I will get a bonus
-- 3. But I did not get a bonus
--     Therefore I played piano
-- Variables: p = Piano, w = worked hard, b = got a bonus
--    (w \/ p) /\ (w => b) /\ ¬(b)
--   ---------------------------
--                p

-- First approach using language control structure if-then-else
w, p, b::Bool
-- Two equivalences for (w \/ p) as an implication.
-- 1. (w \/ p) =equivalent-to=> (not p) => w
-- 2. (w \/ p) =equivalent-to=> (not w) => p
-- Picked 2
p = if (not w) then True else False
-- Contrapositive:  (w => b)  =equivalent-to=>  ~b => ~w
w = if (not b) then False else True
b = False
-- gives p is true and w is false

-- Second approach using pattern matching
-- I think the rewriting goes from left to right but the logical inference goes in the opposite direction.
w1, p1, b1::Bool
p1 = (not w1)
w1 = b1 -- Not consistent with statements, but I do not know how to write ~b1 => ~w1 in Haskell
b1 = False
-- Again gives p1 is true and w1 is false


Tá an teachtaireacht seo scanta ó thaobh ábhar agus víreas ag Seirbhís Scanta Ríomhphost de chuid Seirbhísí Faisnéise, ITBÁC agus meastar í a bheith slán. http://www.dit.ie
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 <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
John | 14 May 2013 16:57
Picon

list comprehension doesn't work

Hi,

I have to write a function which returns a list of all pairs (x,y) where x,
y ∈ N AND:
–  x is the product of two natural numbers (x = a · b, where a, b ∈ N) AND
–  x is really bigger than 5 but really smaller than 500, AND
–  y is a squer number (y = c² where c ∈ N) NOT greater than 1000, AND
–  x is a divisor of y.

My attempt is as follows:

listPairs :: [(Int, Int)]
listPairs = [(x,y) | x<-[0..], y<-[0..], x<-[0..]*[0..], x > 5, x < 500,
(y*y) < 1001, mod y x == 0]

However it doesn't work unfortunatly 

Could anyone tell me where my mistake is?

Thanks.

--
View this message in context: http://haskell.1045720.n5.nabble.com/list-comprehension-doesn-t-work-tp5730158.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Gmane