Search Results

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

Page 23/31 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • mapping list of different types implementing same function?

    - by sisif
    I want to apply a function to every element in a list (map) but the elements may have different types but all implement the same function (here "putOut") like an interface. However I cannot create a list of this "interface" type (here "Outputable"). How do I map a list of different types implementing the same function? main :: IO () main = do map putOut lst putStrLn "end" where lst :: [Outputable] -- ERROR: Class "Outputable" used as a type lst = [(Out1 1),(Out2 1 2)] class Outputable a where putOut :: a -> IO () -- user defined: data Out1 = Out1 Int deriving (Show) data Out2 = Out2 Int deriving (Show) instance Outputable Out1 where putOut out1 = putStrLn $ show out1 instance Outputable Out2 where putOut out2 = putStrLn $ show out2 I cannot define it this way: data Out = Out1 Int | Out2 Int Int putOut Out1 = ... putOut Out2 = ... because this is a library and users should be able to extend Out with their own types

    Read the article

  • Why does s ++ t not lead to a stack overflow for large s?

    - by martingw
    I'm wondering why Prelude> head $ reverse $ [1..10000000] ++ [99] 99 does not lead to a stack overflow error. The ++ in the prelude seems straight forward and non-tail-recursive: (++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys So just with this, it should run into a stack overflow, right? So I figure it probably has something to do with the ghc magic that follows the definition of ++: {-# RULES "++" [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys #-} Is that what helps avoiding the stack overflow? Could someone provide some hint for what's going on in this piece of code?

    Read the article

  • Strange pattern matching with functions instancing Show

    - by Sean D
    So I'm writing a program which returns a procedure for some given arithmetic problem, so I wanted to instance a couple of functions to Show so that I can print the same expression I evaluate when I test. The trouble is that the given code matches (-) to the first line when it should fall to the second. {-# OPTIONS_GHC -XFlexibleInstances #-} instance Show (t -> t-> t) where show (+) = "plus" show (-) = "minus" main = print [(+),(-)] returns [plus,plus] Am I just committing a motal sin printing functions in the first place or is there some way I can get it to match properly? edit:I realise I am getting the following warning: Warning: Pattern match(es) are overlapped In the definition of `show': show - = ... I still don't know why it overlaps, or how to stop it.

    Read the article

  • Are comonads a good fit for modeling the Wumpus world?

    - by Tim Stewart
    I'm trying to find some practical applications of a comonad and I thought I'd try to see if I could represent the classical Wumpus world as a comonad. I'd like to use this code to allow the Wumpus to move left and right through the world and clean up dirty tiles and avoid pits. It seems that the only comonad function that's useful is extract (to get the current tile) and that moving around and cleaning tiles would not use be able to make use of extend or duplicate. I'm not sure comonads are a good fit but I've seen a talk (Dominic Orchard: A Notation for Comonads) where comonads were used to model a cursor in a two-dimensional matrix. If a comonad is a good way of representing the Wumpus world, could you please show where my code is wrong? If it's wrong, could you please suggest a simple application of comonads? module Wumpus where -- Incomplete model of a world inhabited by a Wumpus who likes a nice -- tidy world but does not like falling in pits. import Control.Comonad -- The Wumpus world is made up of tiles that can be in one of three -- states. data Tile = Clean | Dirty | Pit deriving (Show, Eq) -- The Wumpus world is a one dimensional array partitioned into three -- values: the tiles to the left of the Wumpus, the tile occupied by -- the Wumpus, and the tiles to the right of the Wumpus. data World a = World [a] a [a] deriving (Show, Eq) -- Applies a function to every tile in the world instance Functor World where fmap f (World as b cs) = World (fmap f as) (f b) (fmap f cs) -- The Wumpus world is a Comonad instance Comonad World where -- get the part of the world the Wumpus currently occupies extract (World _ b _) = b -- not sure what this means in the Wumpus world. This type checks -- but does not make sense to me. extend f w@(World as b cs) = World (map world as) (f w) (map world cs) where world v = f (World [] v []) -- returns a world in which the Wumpus has either 1) moved one tile to -- the left or 2) stayed in the same place if the Wumpus could not move -- to the left. moveLeft :: World a -> World a moveLeft w@(World [] _ _) = w moveLeft (World as b cs) = World (init as) (last as) (b:cs) -- returns a world in which the Wumpus has either 1) moved one tile to -- the right or 2) stayed in the same place if the Wumpus could not move -- to the right. moveRight :: World a -> World a moveRight w@(World _ _ []) = w moveRight (World as b cs) = World (as ++ [b]) (head cs) (tail cs) initWorld = World [Dirty, Clean, Dirty] Dirty [Clean, Dirty, Pit] -- cleans the current tile cleanTile :: Tile -> Tile cleanTile Dirty = Clean cleanTile t = t Thanks!

    Read the article

  • Adding class constraints to typeclass instance

    - by BleuM937
    I'm trying to implement the Cantor Pairing Function, as an instance of a generic Pair typeclass, as so: module Pair (Pair, CantorPair) where -- Pair interface class Pair p where pi :: a -> a -> p a k :: p a -> a l :: p a -> a -- Wrapper for typing newtype CantorPair a = P { unP :: a } -- Assume two functions with signatures: cantorPair :: Integral a => a -> a -> CantorPair a cantorUnpair :: Integral a => CantorPair a -> (a, a) -- I need to somehow add an Integral a constraint to this instance, -- but I can't work out how to do it. instance Pair CantorPair where pi = cantorPair k = fst . cantorUnpair l = snd . cantorUnpair How can I add the appropriate Integral constraint to the instance? I have a vague feeling I might need to modify the Pair interface itself, but not sure how to go about this.

    Read the article

  • understanding syb boilerplate elimination

    - by Pradeep
    In the example given in http://web.archive.org/web/20080622204226/http://www.cs.vu.nl/boilerplate/ -- Increase salary by percentage increase :: Float -> Company -> Company increase k = everywhere (mkT (incS k)) -- "interesting" code for increase incS :: Float -> Salary -> Salary incS k (S s) = S (s * (1+k)) how come increase function compiles without binding anything for the first Company mentioned in its type signature. Is it something like assigning to a partial function? Why is it done like that?

    Read the article

  • breadth-first traversal of directory tree is not lazy

    - by user855443
    I try to traverse the diretory tree. A naive depth-first traversal seems not to produce the data in a lazy fashion and runs out of memory. I next tried a breadth first approach, which shows the same problem - it uses all the memory available and then crashes. the code i have is: getFilePathBreadtFirst :: FilePath -> IO [FilePath] getFilePathBreadtFirst fp = do fileinfo <- getInfo fp res :: [FilePath] <- if isReadableDirectory fileinfo then do children <- getChildren fp lower <- mapM getFilePathBreadtFirst children return (children ++ concat lower) return (children ++ concat () else return [fp] -- should only return the files? return res getChildren :: FilePath -> IO [FilePath] getChildren path = do names <- getUsefulContents path let namesfull = map (path </>) names return namesfull testBF fn = do -- crashes for /home/frank, does not go to swap fps <- getFilePathBreadtFirst fn putStrLn $ unlines fps I think all the code is either linear or tail recursive, and I would expect that the listing of filenames starts immediately, but in fact it does not. Where is the error in my code and my thinking? where have I lost lazy evaluation?

    Read the article

  • What is considered bleeding edge in programming these days?

    - by iestyn
    What is "bleeding edge" these days? has it all been done before us, and we are just discovering new ways of implementing mathematical constructs within programming? Functional Programming seems to be making inroads in all areas, but is this just marketing to create interest in a programming arena where it appears that the state of the art has climaxed too soon. have the sales men got hold of the script, and selling ideas that can be sold, dumbing down the future? I see very old ideas making their way into the market place....what are the truly new things that should be considered fresh and new in 2010 onwards, and not some 1960-1980 idea being refocused.

    Read the article

  • Strange type-related error

    - by vsb
    I wrote following program: isPrime x = and [x `mod` i /= 0 | i <- [2 .. truncate (sqrt x)]] primes = filter isPrime [1 .. ] it should construct list of prime numbers. But I got this error: [1 of 1] Compiling Main ( 7/main.hs, interpreted ) 7/main.hs:3:16: Ambiguous type variable `a' in the constraints: `Floating a' arising from a use of `isPrime' at 7/main.hs:3:16-22 `RealFrac a' arising from a use of `isPrime' at 7/main.hs:3:16-22 `Integral a' arising from a use of `isPrime' at 7/main.hs:3:16-22 Possible cause: the monomorphism restriction applied to the following: primes :: [a] (bound at 7/main.hs:3:0) Probable fix: give these definition(s) an explicit type signature or use -XNoMonomorphismRestriction Failed, modules loaded: none. If I specify signature for isPrime function explicitly: isPrime :: Integer -> Bool isPrime x = and [x `mod` i /= 0 | i <- [2 .. truncate (sqrt x)]] I can't even compile isPrime function: [1 of 1] Compiling Main ( 7/main.hs, interpreted ) 7/main.hs:2:45: No instance for (RealFrac Integer) arising from a use of `truncate' at 7/main.hs:2:45-61 Possible fix: add an instance declaration for (RealFrac Integer) In the expression: truncate (sqrt x) In the expression: [2 .. truncate (sqrt x)] In a stmt of a list comprehension: i <- [2 .. truncate (sqrt x)] 7/main.hs:2:55: No instance for (Floating Integer) arising from a use of `sqrt' at 7/main.hs:2:55-60 Possible fix: add an instance declaration for (Floating Integer) In the first argument of `truncate', namely `(sqrt x)' In the expression: truncate (sqrt x) In the expression: [2 .. truncate (sqrt x)] Failed, modules loaded: none. Can you help me understand, why am I getting these errors?

    Read the article

  • Collecting IO outputs into list

    - by sisif
    how can i do multiple calls to SDL.pollEvent :: IO Event until the output is SDL.NoEvent and collect all the results into a list? in imperative terms something like this: events = [] event = SDL.pollEvent; while( event != SDL.NoEvent ) events.add( event ) event = SDL.pollEvent

    Read the article

  • Applying a function that may fail to all values in a list

    - by Egwor
    I want to apply a function f to a list of values, however function f might randomly fail (it is in effect making a call out to a service in the cloud). I thought I'd want to use something like map, but I want to apply the function to all elements in the list and afterwards, I want to know which ones failed and which were successful. Currently I am wrapping the response objects of the function f with an error pair which I could then effectively unzip afterwards i.e. something like g : (a->b) -> a -> [ b, errorBoolean] f : a-> b and then to run the code ... map g (xs) Is there a better way to do this? The other alternative approach was to iterate over the values in the array and then return a pair of arrays, one which listed the successful values and one which listed the failures. To me, this seems to be something that ought to be fairly common. Alternatively I could return some special value. What's the best practice in dealing with this??

    Read the article

  • stm monad problem

    - by Alex
    This is just a hypothetical scenario to illustrate my question. Suppose that there are two threads and one TVar shared between them. In one thread there is an atomically block that reads the TVar and takes 10s to complete. In another thread is an atomically block that modifies the TVar every second. Will the first atomically block ever complete? Surely it will just keep going back to the beginning, because the log is in an inconsistent state?

    Read the article

  • Nested Lambdas in wxHaskell Library

    - by kunkelwe
    I've been trying to figure out how I can make staticText elements resize to fit their contents with wxHaskell. From what I can tell, this is the default behavior in wxWidgets, but the wxHaskell wrapper specifically disables this behavior. However, the library code that creates new elements has me very confused. Can anyone provide an explanation for what this code does? staticText :: Window a -> [Prop (StaticText ())] -> IO (StaticText ()) staticText parent props = feed2 props 0 $ initialWindow $ \id rect -> initialText $ \txt -> \props flags -> do t <- staticTextCreate parent id txt rect flags {- (wxALIGN_LEFT + wxST_NO_AUTORESIZE) -} set t props return t I know that feed2 x y f = f x y, and that the type signature of initialWindow is initialWindow :: (Id -> Rect -> [Prop (Window w)] -> Style -> a) -> [Prop (Window w)] -> Style -> a and the signature of initialText is initialText :: Textual w => (String -> [Prop w] -> a) -> [Prop w] -> a but I just can't wrap my head around all the lambdas.

    Read the article

  • Splitting list into a list of possible tuples

    - by user1742646
    I need to split a list into a list of all possible tuples, but I'm unsure of how to do so. For example pairs ["cat","dog","mouse"] should result in [("cat","dog"), ("cat","mouse"), ("dog","cat"), ("dog","mouse"), ("mouse","cat"), ("mouse","dog")] I was able to form the first two, but am unsure of how to get the rest. Here's what I have so far: pairs :: [a] -> [(a,a)] pairs (x:xs) = [(m,n) | m <- [x], n <- xs]

    Read the article

  • How do record updates behave internally?

    - by redxaxder
    data Thing = Thing {a :: Int, b :: Int, c :: Int, (...) , z :: Int} deriving Show foo = Thing 1 2 3 4 5 (...) 26 mkBar x = x { c = 30 } main = do print $ mkBar foo What is copied over when I mutate foo in this way? As opposed to mutating part of a structure directly. Data Thing = Thing {a :: IORef Int, b :: IORef Int, (...) , z :: IORef Int} instance Show Thing where (...something something unsafePerformIO...) mkFoo = do a <- newIORef 1 (...) z <- newIORef 26 return Thing a b (...) z mkBar x = writeIORef (c x) 30 main = do foo <- mkFoo mkBar foo print foo Does compiling with optimizations change this behavior?

    Read the article

  • I can't seem to figure out type variables mixed with classes.

    - by onmach
    I pretty much understand 3/4 the rest of the language, but every time I dip my feet into using classes in a meaningful way in my code I get permantently entrenched. Why doesn't this extremely simple code work? data Room n = Room n n deriving Show class HasArea a where width :: (Num n) => a -> n instance (Num n) => HasArea (Room n) where width (Room w h) = w So, room width is denoted by ints or maybe floats, I don't want to restrict it at this point. Both the class and the instance restrict the n type to Nums, but it still doesn't like it and I get this error: Couldn't match expected type `n1' against inferred type `n' `n1' is a rigid type variable bound by the type signature for `width' at Dungeon.hs:11:16 `n' is a rigid type variable bound by the instance declaration at Dungeon.hs:13:14 In the expression: w In the definition of `width': width (Room w h) = w In the instance declaration for `HasArea (Room n)' So it tells me the types doesn't match, but it doesn't tell me what types it thinks they are, which would be really helpful. As a side note, is there any easy way to debug an error like this? The only way I know to do it is to randomly change stuff until it works.

    Read the article

  • What advantage does Monad give us over an Applicative?

    - by arrowdodger
    I've read this article, but didn't understand last section. The author says that Monad gives us context sensitivity, but it's possible to achieve the same result using only an Applicative instance: let maybeAge = (\futureYear birthYear -> if futureYear < birthYear then yearDiff birthYear futureYear else yearDiff futureYear birthYear) <$> (readMay futureYearString) <*> (readMay birthYearString) It's uglier for sure, but beside that I don't see why we need Monad. Can anyone clear this up for me?

    Read the article

  • Why is writeSTRef faster than if expression?

    - by wenlong
    writeSTRef twice for each iteration fib3 :: Int -> Integer fib3 n = runST $ do a <- newSTRef 1 b <- newSTRef 1 replicateM_ (n-1) $ do !a' <- readSTRef a !b' <- readSTRef b writeSTRef a b' writeSTRef b $! a'+b' readSTRef b writeSTRef once for each iteration fib4 :: Int -> Integer fib4 n = runST $ do a <- newSTRef 1 b <- newSTRef 1 replicateM_ (n-1) $ do !a' <- readSTRef a !b' <- readSTRef b if a' > b' then writeSTRef b $! a'+b' else writeSTRef a $! a'+b' a'' <- readSTRef a b'' <- readSTRef b if a'' > b'' then return a'' else return b'' Benchmark, given n = 20000: benchmarking 20000/fib3 mean: 5.073608 ms, lb 5.071842 ms, ub 5.075466 ms, ci 0.950 std dev: 9.284321 us, lb 8.119454 us, ub 10.78107 us, ci 0.950 benchmarking 20000/fib4 mean: 5.384010 ms, lb 5.381876 ms, ub 5.386099 ms, ci 0.950 std dev: 10.85245 us, lb 9.510215 us, ub 12.65554 us, ci 0.950 fib3 is a bit faster than fib4.

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >