Search Results

Search found 762 results on 31 pages for 'haskell'.

Page 20/31 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • Demangling typeclass functions in GHC profiler output

    - by Paul Kuliniewicz
    When profiling a Haskell program written in GHC, the names of typeclass functions are mangled in the .prof file to distinguish one instance's implementations of them from another. How can I demangle these names to find out which type's instance it is? For example, suppose I have the following program, where types Fast and Slow both implement Show: import Data.List (foldl') sum' = foldl' (+) 0 data Fast = Fast instance Show Fast where show _ = show $ sum' [1 .. 10] data Slow = Slow instance Show Slow where show _ = show $ sum' [1 .. 100000000] main = putStrLn (show Fast ++ show Slow) I compile with -prof -auto-all -caf-all and run with +RTS -p. In the .prof file that gets generated, I see that the top cost centers are: COST CENTRE MODULE %time %alloc show_an9 Main 71.0 83.3 sum' Main 29.0 16.7 And in the tree, I likewise see (omitting irrelevant lines): individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc main Main 232 1 0.0 0.0 100.0 100.0 show_an9 Main 235 1 71.0 83.3 100.0 100.0 sum' Main 236 0 29.0 16.7 29.0 16.7 show_anx Main 233 1 0.0 0.0 0.0 0.0 How do I figure out that show_an9 is Slow's implementation of show and not Fast's?

    Read the article

  • How to use the `itemDoubleClicked(QTreeWidgetItem*,int)` signal in qtHaskell

    - by nano
    I want to use the itemDoubleClicked(QTreeWidgetItem*,int) signal in a Haskell program I'm writing where I am using qtHaskell for the GUI. To connect a function I have at other places done the following: dummyWidget <- myQWidget connectSlot object signal dummyWidget "customSlot()" $ f Where object is some QWidget and signal is a string giving the signal, e.g. "triggered()", and f is the function I want to be called when the signaled is send. The definition of connectSlot in the API is: class Qcs x where connectSlot :: QObject a -> String -> QObject b -> String -> x -> IO () where the instances ofQcs are: Qcs () Qcs (QObject c -> String -> IO ()) Qcs (QObject c -> Object d -> IO ()) Qcs (QObject c -> Bool -> IO ()) Qcs (QObject c -> Int -> IO ()) Qcs (QObject c -> IO ()) Qcs (QObject c -> OpenGLVersionFlag -> IO ()) The first Arguments passed is supposed to be the QObject of which I'm using a signal. As you can see, there is no instance where f, the function to connect to the signal, can have two further arguments to recieve the QWidget and the integer send by the signal. Is there a way to nevertheless connect that signal to a custom function?

    Read the article

  • Pseudo-quicksort time complexity

    - by Ord
    I know that quicksort has O(n log n) average time complexity. A pseudo-quicksort (which is only a quicksort when you look at it from far enough away, with a suitably high level of abstraction) that is often used to demonstrate the conciseness of functional languages is as follows (given in Haskell): quicksort :: Ord a => [a] -> [a] quicksort [] = [] quicksort (p:xs) = quicksort [y | y<-xs, y<p] ++ [p] ++ quicksort [y | y<-xs, y>=p] Okay, so I know this thing has problems. The biggest problem with this is that it does not sort in place, which is normally a big advantage of quicksort. Even if that didn't matter, it would still take longer than a typical quicksort because it has to do two passes of the list when it partitions it, and it does costly append operations to splice it back together afterwards. Further, the choice of the first element as the pivot is not the best choice. But even considering all of that, isn't the average time complexity of this quicksort the same as the standard quicksort? Namely, O(n log n)? Because the appends and the partition still have linear time complexity, even if they are inefficient.

    Read the article

  • Appropriate uses of Monad `fail` vs. MonadPlus `mzero`

    - by jberryman
    This is a question that has come up several times for me in the design code, especially libraries. There seems to be some interest in it so I thought it might make a good community wiki. The fail method in Monad is considered by some to be a wart; a somewhat arbitrary addition to the class that does not come from the original category theory. But of course in the current state of things, many Monad types have logical and useful fail instances. The MonadPlus class is a sub-class of Monad that provides an mzero method which logically encapsulates the idea of failure in a monad. So a library designer who wants to write some monadic code that does some sort of failure handling can choose to make his code use the fail method in Monad or restrict his code to the MonadPlus class, just so that he can feel good about using mzero, even though he doesn't care about the monoidal combining mplus operation at all. Some discussions on this subject are in this wiki page about proposals to reform the MonadPlus class. So I guess I have one specific question: What monad instances, if any, have a natural fail method, but cannot be instances of MonadPlus because they have no logical implementation for mplus? But I'm mostly interested in a discussion about this subject. Thanks! EDIT: One final thought occured to me. I recently learned (even though it's right there in the docs for fail) that monadic "do" notation is desugared in such a way that pattern match failures, as in (x:xs) <- return [] call the monad's fail. It seems like the language designers must have been strongly influenced by the prospect of some automatic failure handling built in to haskell's syntax in their inclusion of fail in Monad.

    Read the article

  • Haskel dot (.) and dollar ($) composition: correct use.

    - by Robert Massaioli
    I have been reading Real World Haskell and I am nearing the end but a matter of style has been niggling at me to do with the (.) and ($) operators. When you write a function that is a composition of other functions you write it like: f = g . h But when you apply something to the end of those functions I write it like this: k = a $ b $ c $ value But the book would write it like this: k = a . b . c $ value Now to me they look functionally equivalent, they do the exact same thing in my eyes. However, the more I look, the more I see people writing their functions in the manner that the book does: compose with (.) first and then only at the end use ($) to append a value to evaluate the lot (nobody does it with many dollar compositions). Is there a reason for using the books way that is much better than using all ($) symbols? Or is there some best practice here that I am not getting? Or is it superfluous and I shouldn't be worrying about it at all? Thanks.

    Read the article

  • Using items in a list as arguments

    - by Travis Brown
    Suppose I have a function with the following type signature: g :: a -> a -> a -> b I also have a list of as—let's call it xs—that I know will contain at least three items. I'd like to apply g to the first three items of xs. I know I could define a combinator like the following: ($$$) :: (a -> a -> a -> b) -> [a] -> b f $$$ (x:y:z:_) = f x y z Then I could just use g $$$ xs. This makes $$$ a bit like uncurry, but for a function with three arguments of the same type and a list instead of a tuple. Is there a way to do this idiomatically using standard combinators? Or rather, what's the most idiomatic way to do this in Haskell? I thought trying pointfree on a non-infix version of $$$ might give me some idea of where to start, but the output was an abomination with 10 flips, a handful of heads and tails and aps, and 28 parentheses. (NB: I know this isn't a terribly Haskelly thing to do in the first place, but I've come across a couple of situations where it seems like a reasonable solution, especially when using Parsec. I'll certainly accept "don't ever do this in real code" if that's the best answer, but I'd prefer to see some clever trick involving the ((->) r) monad or whatever.)

    Read the article

  • Problem with incomplete input when using Attoparsec

    - by Dan Dyer
    I am converting some functioning Haskell code that uses Parsec to instead use Attoparsec in the hope of getting better performance. I have made the changes and everything compiles but my parser does not work correctly. I am parsing a file that consists of various record types, one per line. Each of my individual functions for parsing a record or comment works correctly but when I try to write a function to compile a sequence of records the parser always returns a partial result because it is expecting more input. These are the two main variations that I've tried. Both have the same problem. items :: Parser [Item] items = sepBy (comment <|> recordType1 <|> recordType2) endOfLine For this second one I changed the record/comment parsers to consume the end-of-line characters. items :: Parser [Item] items = manyTill (comment <|> recordType1 <|> recordType2) endOfInput Is there anything wrong with my approach? Is there some other way to achieve what I am attempting?

    Read the article

  • Could someone explain gtk2hs drag and drop to me, the listDND.hs demo just isn't doing it for me?

    - by Tom Carstens
    As the title says, I just don't get DND (or rather I understand the concept and I understand the order of callbacks, I just don't understand how to setup DND for actual usage.) I'd like to say that I've done DND stuff before in C, but considering I never really got that working... So I'm trying (and mostly succeeding, save DND) to write a text editor (using gtksourceview, because it has built in code highlighting.) Reasons are below if you want them. Anyways, there's not really a good DND demo or tutorial available for gtk2hs (listDND.hs just doesn't translate well in my head.) So what I'm asking is for code that demonstrates simple DND on a window widget (for example.) Ideally, it should accept drops from other windows (such as Thunar) and print out the information in string form. I think I can take it from there... Reasons: I'm running a fairly light weight setup, dwm and a few gtk+2 programs. I really don't want to have to pull in gtk+3 to get the current gedit from the repos (Arch Linux.) Currently, I'm using geany for all of my text editing needs, however, geany is a bit heavy for editing config files. Further, geany doesn't care for my terminal of choice (st;) so I don't even get the benefit of using it as an IDE. Meaning I'd like a lightweight text editor with syntax highlighting. I could configure emacs or vim or something, but that seems to me to be more of a hack then a proper solution. Thus my project was born. It's mostly working (aside from DND, all that's left is proper multi-tab support.) Admittedly, I could probably work this out if I wrote it in C, but there isn't that much state in a text editor so Haskell's been working fine with almost no need for mutable variables.

    Read the article

  • Flowcharting functional programming languages

    - by Sadface
    Flowcharting. This ancient old practice that's been in use for over 1000 years now, being forced upon us poor students, without any usefulness (or so do I think). It might work well with imperative, sequentially running languages, but what about my beloved functional programming? Sadly, I'm forced to create a flow chart for my programm (that is written in Haskell). I imagine it being easy for something like this: main :: IO () main = do someInput <- getLine let upped = map toUpper someInput putStrLn upped Which is just 3 sequenced steps, fetching data, uppercasing it, outputting it. Things look worse this time: main :: IO () main = do someInput <- fmap toUpper getLine putStrLn someInput Or like this: main :: IO () main = interact (map toUpper) Okay, that was IO, you can handle that like an imperative language. What about pure functions? An actual example: onlyMatching :: String -> [FilePath] -> [FilePath] onlyMatching ext = filter f where f name = lower ('.' : ext) == (lower . takeExtension $ name) lower = map toLower How would you flowchart that last one?

    Read the article

  • Heap Algorithmic Issue

    - by OberynMarDELL
    I am having this algorithmic problem that I want to discuss about. Its not about find a solution but about optimization in terms of runtime. So here it is: Suppose we have a race court of Length L and a total of N cars that participate on the race. The race rules are simple. Once a car overtakes an other car the second car is eliminated from the race. The race ends when no more overtakes are possible to happen. The tricky part is that the k'th car has a starting point x[k] and a velocity v[k]. The points are given in an ascending order, but the velocities may differ. What I've done so far: Given that a car can get overtaken only by its previous, I calculated the time that it takes for each car to reach its next one t = (x[i] - x[i+1])/(v[i] - v[i+1]) and I insert these times onto a min heap in O(n log n). So in theory I have to pop the first element in O(logn), find its previous, pop it as well , update its time and insert it in the heap once more, much like a priority queue. My main problem is how I can access specific points of a heap in O(log n) or faster in order to keep the complexity in O(n log n) levels. This program should be written on Haskell so I would like to keep things simple as far as possible EDIT: I Forgot to write the actual point of the race. The goal is to find the order in which cars exit the game

    Read the article

  • trouble with state monad composition

    - by user1308560
    I was trying out the example given at http://www.haskell.org/haskellwiki/State_Monad#Complete_and_Concrete_Example_1 How this makes the solution composible is beyond my understanding. Here is what I tried but I get compile errors as follows: Couldn't match expected type `GameValue -> StateT GameState Data.Functor.Identity.Identity b0' with actual type `State GameState GameValue' In the second argument of `(>>=)', namely `g2' In the expression: g1 >>= g2 In an equation for `g3': g3 = g1 >>= g2 Failed, modules loaded: none. Here is the code: See the end lines module StateGame where import Control.Monad.State type GameValue = Int type GameState = (Bool, Int) -- suppose I want to play one game after the other g1 = playGame "abcaaacbbcabbab" g2 = playGame "abcaaacbbcabb" g3 = g1 >>= g2 m2 = print $ evalState g3 startState playGame :: String -> State GameState GameValue playGame [] = do (_, score) <- get return score playGame (x:xs) = do (on, score) <- get case x of 'a' | on -> put (on, score + 1) 'b' | on -> put (on, score - 1) 'c' -> put (not on, score) _ -> put (on, score) playGame xs startState = (False, 0) main str = print $ evalState (playGame str) startState

    Read the article

  • Monads with Join() instead of Bind()

    - by MathematicalOrchid
    Monads are usually explained in turns of return and bind. However, I gather you can also implement bind in terms of join (and fmap?) In programming languages lacking first-class functions, bind is excruciatingly awkward to use. join, on the other hand, looks quite easy. I'm not completely sure I understand how join works, however. Obviously, it has the [Haskell] type join :: Monad m = m (m x) - m x For the list monad, this is trivially and obviously concat. But for a general monad, what, operationally, does this method actually do? I see what it does to the type signatures, but I'm trying to figure out how I'd write something like this in, say, Java or similar. (Actually, that's easy: I wouldn't. Because generics is broken. ;-) But in principle the question still stands...) Oops. It looks like this has been asked before: Monad join function Could somebody sketch out some implementations of common monads using return, fmap and join? (I.e., not mentioning >>= at all.) I think perhaps that might help it to sink in to my dumb brain...

    Read the article

  • How can I bind the second argument in a function but not the first (in an elegant way)?

    - by Frank Osterfeld
    Is there a way in Haskell to bind the second argument but not the first of a function without using lambda functions or defining another "local" function? Example. I have a binary function like: sub :: Int -> Int -> Int sub x y = x - y Now if I want to bind the first argument, I can do so easily using (sub someExpression): mapSubFrom5 x = map (sub 5) x *Main> mapSubFrom5 [1,2,3,4,5] [4,3,2,1,0] That works fine if I want to bind the first n arguments without "gap". If I want to bind the second argument but not the first, the two options I am aware of are more verbose: Either via another, local, function: mapSub5 x = map sub5 x where sub5 x = sub x 5 *Main> mapSub5 [1,2,3,4,5] [-4,-3,-2,-1,0] Or using lambda: mapSub5 x = map (\x -> sub x 5) x While both are working fine, I like the elegance of "sub 5" and wonder if there is a similarly elegant way to bind the n-th (n 1) argument of a function?

    Read the article

  • many1 no longer works with Parsec 3.x

    - by Zak
    After updating to Parsec 3.1 from 2.x, code using many1, such as word = many1 letter fails with No instance for (Stream s m Char) arising from a use of `letter' I found a mailing list post claiming that adding {-#LANGUAGE NoMonomorphismRestriction #-} to the top of the source file would solve the problem, but it did not.

    Read the article

  • Parsec: backtracking not working

    - by Nathan Sanders
    I am trying to parse F# type syntax. I started writing an [F]Parsec grammar and ran into problems, so I simplified the grammar down to this: type ::= identifier | type -> type identifier ::= [A-Za-z0-9.`]+ After running into problems with FParsec, I switched to Parsec, since I have a full chapter of a book dedicated to explaining it. My code for this grammar is typeP = choice [identP, arrowP] identP = do id <- many1 (digit <|> letter <|> char '.' <|> char '`') -- more complicated code here later return id arrowP = do domain <- typeP string "->" range <- typeP return $ "("++domain++" -> "++range++")" run = parse (do t <- typeP eof return t) "F# type syntax" The problem is that Parsec doesn't backtrack by default, so > run "int" Right "int" -- works! > run "int->int" Left "F# type syntax" unexpected "-" expecting digit, letter, ".", "`" or end of input -- doesn't work! The first thing I tried was to reorder typeP: typeP = choice [arrowP, identP] But this just stack overflows because the grammar is left-recursive--typeP never gets to trying identP because it keeps trying arrowP over and over. Next I tried try in various places, for example: typeP = choice [try identP, arrowP] But nothing I do seems to change the basic behaviours of (1) stack overflow or (2) non-recognition of "-" following an identifier. My mistake is probably obvious to anybody who has successfully written a Parsec grammar. Can somebody point it out?

    Read the article

  • Type error while trying to implement the (>>=) function in order to create a custom monad transforme

    - by CharlieP
    Hello, I'm trying to create a monad transformer for a future project, but unfortunately, my implementation of the Monad typeclasse's (=) function doesn't work. First of all, here is the underlying monad's implementation : newtype Runtime a = R { unR :: State EInfo a } deriving (Monad) Here, the implementation of the Monad typeclasse is done automatically by GHC (using the GeneralizedNewtypeDeriving language pragma). The monad transformer is defined as so : newtype RuntimeT m a = RuntimeT { runRuntimeT :: m (Runtime a) } The problem comes from the way I instanciate the (=) function of the Monad typeclasse : instance (Monad m) => Monad (RuntimeT m) where return a = RuntimeT $ (return . return) a x >>= f = runRuntimeT x >>= id >>= f The way I see it, the first >>= runs in the underlying m monad. Thus, runRuntimeT x >>= returns a value of type Runtime a (right ?). Then, the following code, id >>=, should return a value of type a. This value is the passed on to the function f of type f :: (Monad m) => a -> RuntimeT m b. And here comes the type problem : the f function's type doesn't match the type required by the (=) function. Jow can I make this coherent ? I can see why this doesn't work, but I can't manage to turn it into something functionnal. Thank you for you help, and do not hesitate to correct any flaws in my message, Charlie P.

    Read the article

  • How to Convert Type in Tuples

    - by Pradeep
    how to convert a String type to a Int i have a tuple and i want to convert it to a tuple which has different types tupletotuple :: (String,String,String) ->(String,Int,Int) tupletotuple (a,b,c) = (a,read(b),read(c)) i get this Error Msg Project tupletotuple ("cha",4,3) ERROR - Cannot infer instance * Instance : Num [Char] * Expression : tupletotuple ("cha",4,3)

    Read the article

  • Removing the contents of a Chan or MVar in a single discrete step

    - by Bill
    I'm writing a discrete simulation where request values from multiple threads accumulate in a centralized queue. Every n milliseconds, a manager wakes up to process requests. When the manager wakes up, it should retrieve all of the contents of the central queue in a single discrete step. While processing these, any client threads attempting to submit to the queue should block. When processing completes, the queue reopens and the manager goes back to sleep. What's the best way to do this? The retry behavior of STM isn't really what I want. If I use a Chan or MVar, there's no way to prevent clients from enqueuing additional requests during processing. One approach is to use an MVar as a mutex on a Chan holding the queue. Are there other ways to do this?

    Read the article

  • How does 'lazy' work?

    - by Matt Fenwick
    What is the difference between these two functions? I see that lazy is intended to be lazy, but I don't understand how that is accomplished. -- | Identity function. id :: a -> a id x = x -- | The call '(lazy e)' means the same as 'e', but 'lazy' has a -- magical strictness property: it is lazy in its first argument, -- even though its semantics is strict. lazy :: a -> a lazy x = x -- Implementation note: its strictness and unfolding are over-ridden -- by the definition in MkId.lhs; in both cases to nothing at all. -- That way, 'lazy' does not get inlined, and the strictness analyser -- sees it as lazy. Then the worker/wrapper phase inlines it. -- Result: happiness Tracking down the note in MkId.lhs (hopefully this is the right note and version, sorry if it's not): Note [lazyId magic] ~~~~~~~~~~~~~~~~~~~ lazy :: forall a?. a? -> a? (i.e. works for unboxed types too) Used to lazify pseq: pseq a b = a `seq` lazy b Also, no strictness: by being a built-in Id, all the info about lazyId comes from here, not from GHC.Base.hi. This is important, because the strictness analyser will spot it as strict! Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep. It's very important to do this inlining after unfoldings are exposed in the interface file. Otherwise, the unfolding for (say) pseq in the interface file will not mention 'lazy', so if we inline 'pseq' we'll totally miss the very thing that 'lazy' was there for in the first place. See Trac #3259 for a real world example. lazyId is defined in GHC.Base, so we don't have to inline it. If it appears un-applied, we'll end up just calling it. I don't understand that because it refers to lazyId instead of lazy. How does lazy work?

    Read the article

  • I'm working on Peano Axioms in Agda and I've hit a bit of a sticking point

    - by Schroedinger
    PA6 : ?{m n} -> m = n -> n = m is the axiom I am trying to solve and support, I've tried using a cong (from the core library) but am having troubles with the cong constructor PA6 = cong gets me nowhere, I know for cong I am required to supply a refl for equality and a type, but I'm, not sure what type I'm supposed to supply. Ideas? This is for a small assignment at University, so I'd rather someone demonstrate what I've missed rather than write the acutual answer, but I'd appreciate any degree of support.

    Read the article

  • Getting Cabal to work with GHC 6.12.1

    - by Dan Dyer
    I've installed the latest GHC package (6.12.1) on OS X, but I can't get Cabal to work. I've removed the version I had previously that worked with GHC 6.10 and tried to re-install from scratch. The latest Cabal version available for download is 1.6.0.2. However, when I try to build this I get the following error: Configuring Cabal-1.6.0.2... Setup: failed to parse output of 'ghc-pkg dump' From what I've found searching, this seems to suggest that the version of Cabal is too old for the version of GHC. Is there any way to get Cabal to work with GHC 6.12.1 yet? EDIT: To be clear, I'm trying to set-up cabal-install.

    Read the article

  • displaying database content in wxHaskell

    - by snorlaks
    Hello, Im using tutorials from wxHaskell and want to display content of table movies in the grid. HEre is my code : {-------------------------------------------------------------------------------- Test Grid. --------------------------------------------------------------------------------} module Main where import Graphics.UI.WX import Graphics.UI.WXCore hiding (Event) import Database.HDBC.Sqlite3 (connectSqlite3) import Database.HDBC main = start gui gui :: IO () gui = do f <- frame [text := "Grid test", visible := False] -- grids g <- gridCtrl f [] gridSetGridLineColour g (colorSystem Color3DFace) gridSetCellHighlightColour g black appendColumns g (movies) -- Here is error: -- Couldn't match expected type [String]' -- against inferred typeIO [[String]]' --appendRows g (map show [1..length (tail movies)]) --mapM_ (setRow g) (zip [0..] (tail movies)) gridAutoSize g -- layout set f [layout := column 5 [fill (dynamic (widget g))] ] focusOn g set f [visible := True] -- reduce flicker at startup. return () where movies = do conn <- connectSqlite3 "Spop.db" r <- quickQuery' conn "SELECT id, title, year, description from Movie where id = 1" [] let myResult = map convRow r return myResult setRow g (row,values) = mapM_ ((col,value) - gridSetCellValue g row col value) (zip [0..] values) {-------------------------------------------------------------------------------- Library?f --------------------------------------------------------------------------------} gridCtrl :: Window a - [Prop (Grid ())] - IO (Grid ()) gridCtrl parent props = feed2 props 0 $ initialWindow $ \id rect - \props flags - do g <- gridCreate parent id rect flags gridCreateGrid g 0 0 0 set g props return g appendColumns :: Grid a - [String] - IO () appendColumns g [] = return () appendColumns g labels = do n <- gridGetNumberCols g gridAppendCols g (length labels) True mapM_ ((i,label) - gridSetColLabelValue g i label) (zip [n..] labels) appendRows :: Grid a - [String] - IO () appendRows g [] = return () appendRows g labels = do n <- gridGetNumberRows g gridAppendRows g (length labels) True mapM_ ((i,label) - gridSetRowLabelValue g i label) (zip [n..] labels) convRow :: [SqlValue] - [String] convRow [sqlId, sqlTitle, sqlYear, sqlDescription] = [intid, title, year, description] where intid = (fromSql sqlId)::String title = (fromSql sqlTitle)::String year = (fromSql sqlYear)::String description = (fromSql sqlDescription)::String What should I do to get rif of error in code above (24th line)

    Read the article

  • Continuation monad "interface"

    - by sdcvvc
    The state monad "interface" class MonadState s m where get :: m s put :: s -> m () (+ return and bind) allows to construct any possible computation with State monad without using State constructor. For example, State $ \s -> (s+1, s-1) can be written as do s <- get put (s-1) return (s+1) Similarily, I never have to use Reader constructor, because I can create that computation using ask, return and (>>=). Precisely: Reader f == ask >>= return . f. Is it the same true for continuations - is it possible to write all instances of Cont r a using callCC (the only function in MonadCont), return and bind, and never type something like Cont (\c -> ...)?

    Read the article

  • "Ambigous type variable" error when defining custom "read" function

    - by Tener
    While trying to compile the following code, which is enhanced version of read build on readMay from Safe package. readI :: (Typeable a, Read a) => String -> a readI str = case readMay str of Just x -> x Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf > (undefined :: a))) ++ "String was: " ++ str) I get an error from GHC: WavefrontSimple.hs:54:81: Ambiguous type variable `a' in the constraint: `Typeable a' arising from a use of `typeOf' at src/WavefrontSimple.hs:54:81-103 Probable fix: add a type signature that fixes these type variable(s)` I don't understand why. What should be fixed to get what I meant? EDIT: Ok, so the solution to use ScopedTypeVariables and forall a in type signature works. But why the following produces very similar error to the one above? The compiler should infer the right type since there is asTypeOf :: a -> a -> a used. readI :: (Typeable a, Read a) => String -> a readI str = let xx = undefined in case readMay str of Just x -> x `asTypeOf` xx Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf xx)) ++ "String was: " ++ str)

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >