[Haskell-beginners] Code works in a file but not the interpreter

Daniel Fischer daniel.is.fischer at web.de
Sat May 1 06:15:29 EDT 2010


Am Samstag 01 Mai 2010 06:39:47 schrieb Oge:
> Hi all,
>
> This is my first post to haskell-beginners. I am trying to use the
> SegmentTree-0.2 library from Hackage but I get an error when I try to
> use some of its functions. For instance when I load a file containing
> the following
>
> module Stabbing.SegmentTree (counts) where
> import Data.SegmentTree
>
> counts :: [(Rational, Rational)] -> [Rational] -> [Integer]
> counts intervals points = map (countingQuery segmentTree) points
>   where
>     segmentTree = fromList intervals
>
> in the GHC interpreter (6.10.3), my interactions look as such
>
> *Stabbing.SegmentTree> counts [(4, 5)] [3]
> [0]
> *Stabbing.SegmentTree> fromList [(4, 5)]
>
> <interactive>:1:0:
>     No instance for (SegmentTree-0.2:Data.SegmentTree.Measured.Measured
>
> (SegmentTree-0.2:Data.SegmentTree.Interval.Interval t) t1)
>       arising from a use of `fromList' at <interactive>:1:0-16
>     Possible fix:
>       add an instance declaration for
>       (SegmentTree-0.2:Data.SegmentTree.Measured.Measured
>          (SegmentTree-0.2:Data.SegmentTree.Interval.Interval t) t1)
>     In the expression: fromList [(4, 5)]
>     In the definition of `it': it = fromList [(4, 5)]
>
> As you can see, "fromList intervals" is a sub-expression of counts,
> but when I try to evaluate a similar expression at the interpreter, I
> get an error. Does anyone know what the problem is? This is not the
> "No instance for (Show ..." error that I'm used to.
>
> Ogechi Nnadi.

Well,

fromList :: (Monoid t, Measured (Interval a) t, Ord a) 
        => [(a, a)] -> STree t a

, so in fromList [(4,5)], it doesn't know what types to use for t and a, 
hence the error message that says it doesn't have an instance of Measured 
for two arbitrary types.

In counts, the result of fromList, segmentTree, is used as the first 
argument of

countingQuery :: (Measured (Interval a) (Sum b), Ord a) 
        => STree (Sum b) a -> a -> b

which resolves the 't' in fromList's type as 'Sum b' - not yet much 
progress, but the type signature

counts :: [(Rational, Rational)] -> [Rational] -> [Integer]

fixes the types, a is Rational and b is (Sum Integer). Now the compiler 
knows exactly what types to use, since the constraints of fromList -
(Monoid (Sum Integer), Measured (Interval Rational) (Sum Integer), Ord 
Rational) - and countingQuery -
(Measured (Interval Rational) (Sum Integer); Ord Rational) - are fulfilled, 
it works.

If you tell ghci which types to use in

fromList [(4,5)]

, say

fromList [(4,5)] :: STree (Sum Integer) Rational

(you probably need to bring Data.Monoid into scope - import into your 
module or ":m +Data.Monoid" in ghci - to have 'Sum' available), that will 
work too.


More information about the Beginners mailing list