Search Results

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

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

  • Confusion regarding laziness

    - by Abhinav Kaushik
    I have a function myLength = foldl (\ x _ -> x + 1) 0 which fails with stack overflow with input around 10^6 elements (myLength [1..1000000] fails). I believe that is due to the thunk build up since when I replace foldl with foldl', it works. So far so good. But now I have another function to reverse a list : myReverse = foldl (\ acc x -> x : acc) [] which uses the lazy version foldl (instead of foldl') When I do myLength . myReverse $ [1.1000000]. This time it works fine. I fail to understand why foldl works for the later case and not for former?

    Read the article

  • "Pattern matching" of algebraic type data constructors

    - by jetxee
    Let's consider a data type with many constructors: data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int I want to write a function to check if two values are produced with the same constructor: sameK (Alpha _) (Alpha _) = True sameK (Beta _) (Beta _) = True sameK (Gamma _ _) (Gamma _ _) = True sameK _ _ = False Maintaining sameK is not much fun, it is potentially buggy. For example, when new constructors are added to T, it's easy to forget to update sameK. I omitted one line to give an example: -- it’s easy to forget: -- sameK (Delta _) (Delta _) = True The question is how to avoid boilerplate in sameK? Or how to make sure it checks for all T constructors? The workaround I found is to use separate data types for each of the constructors, deriving Data.Typeable, and declaring a common type class, but I don't like this solution, because it is much less readable and otherwise just a simple algebraic type works for me: {-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable class Tlike t where value :: t -> t value = id data Alpha = Alpha Int deriving Typeable data Beta = Beta Int deriving Typeable data Gamma = Gamma Int Int deriving Typeable data Delta = Delta Int deriving Typeable instance Tlike Alpha instance Tlike Beta instance Tlike Gamma instance Tlike Delta sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool sameK a b = typeOf a == typeOf b

    Read the article

  • hackage package dependencies and future-proof libraries

    - by yairchu
    In the dependencies section of a cabal file: Build-Depends: base >= 3 && < 5, transformers >= 0.2.0 Should I be doing something like Build-Depends: base >= 3 && < 5, transformers >= 0.2.0 && < 0.3.0 (putting upper limits on versions of packages I depend on) or not? I'll use a real example: my "List" package on Hackage (List monad transformer and class) If I don't put the limit - my package could break by a change in "transformers" If I do put the limit - a user that uses "transformers" but is using a newer version of it will not be able to use lift and liftIO with ListT because it's only an instance of these classes of transformers-0.2.x I guess that applications should always put upper limits so that they never break, so this question is only about libraries: Shall I use the upper version limit on dependencies or not?

    Read the article

  • Examples of attoparsec in parsing binary file formats?

    - by me2
    Previously attoparsec was suggested to me for parsing complex binary file formats. While I can find examples of attoparsec parsing HTTP, which is essentially text based, I cannot find an example parsing actual binary, for example, a TCP packet, or image file, or mp3. Can someone post some code or pointer to some code which does this using attoparsec?

    Read the article

  • Is there a good way to QuickCheck Happstack.State methods?

    - by Paul Kuliniewicz
    I have a set of Happstack.State MACID methods that I want to test using QuickCheck, but I'm having trouble figuring out the most elegant way to accomplish that. The problems I'm running into are: The only way to evaluate an Ev monad computation is in the IO monad via query or update. There's no way to create a purely in-memory MACID store; this is by design. Therefore, running things in the IO monad means there are temporary files to clean up after each test. There's no way to initialize a new MACID store except with the initialValue for the state; it can't be generated via Arbitrary unless I expose an access method that replaces the state wholesale. Working around all of the above means writing methods that only use features of MonadReader or MonadState (and running the test inside Reader or State instead of Ev. This means forgoing the use of getRandom or getEventClockTime and the like inside the method definitions. The only options I can see are: Run the methods in a throw-away on-disk MACID store, cleaning up after each test and settling for starting from initialValue each time. Write the methods to have most of the code run in a MonadReader or MonadState (which is more easily testable), and rely on a small amount of non-QuickCheck-able glue around it that calls getRandom or getEventClockTime as necessary. Is there a better solution that I'm overlooking?

    Read the article

  • Binding type variables that only occur in assertions

    - by Giuseppe Maggiore
    Hi! I find it extremely difficult to describe my problem, so here goes nothing: I have a bunch of assertions on the type of a function. These assertions rely on a type variable that is not used for any parameter of the function, but is only used for internal bindings. Whenever I use this function it does not compile because, of course, the compiler has no information from which to guess what type to bind my type variable. Here is the code: {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables, TypeOperators, TypeSynonymInstances #-} class C a a' where convert :: a -> a' class F a b where apply :: a -> b class S s a where select :: s -> a data CInt = CInt Int instance S (Int,String) Int where select (i,_) = i instance F Int CInt where apply = CInt f :: forall s a b . (S s a, F a b) => s -> b f s = let v = select s :: a y = apply v :: b in y x :: Int x = f (10,"Pippo") And here is the generated error: FunctorsProblems.hs:21:4: No instances for (F a Int, S (t, [Char]) a) arising from a use of `f' at FunctorsProblems.hs:21:4-17 Possible fix: add an instance declaration for (F a Int, S (t, [Char]) a) In the expression: f (10, "Pippo") In the definition of `x': x = f (10, "Pippo") Failed, modules loaded: none. Prelude>

    Read the article

  • Use QuickCheck by generating primes

    - by Dan
    Background For fun, I'm trying to write a property for quick-check that can test the basic idea behind cryptography with RSA. Choose two distinct primes, p and q. Let N = p*q e is some number relatively prime to (p-1)(q-1) (in practice, e is usually 3 for fast encoding) d is the modular inverse of e modulo (p-1)(q-1) For all x such that 1 < x < N, it is always true that (x^e)^d = x modulo N In other words, x is the "message", raising it to the eth power mod N is the act of "encoding" the message, and raising the encoded message to the dth power mod N is the act of "decoding" it. (The property is also trivially true for x = 1, a case which is its own encryption) Code Here are the methods I have coded up so far: import Test.QuickCheck -- modular exponentiation modExp :: Integral a => a -> a -> a -> a modExp y z n = modExp' (y `mod` n) z `mod` n where modExp' y z | z == 0 = 1 | even z = modExp (y*y) (z `div` 2) n | odd z = (modExp (y*y) (z `div` 2) n) * y -- relatively prime rPrime :: Integral a => a -> a -> Bool rPrime a b = gcd a b == 1 -- multiplicative inverse (modular) mInverse :: Integral a => a -> a -> a mInverse 1 _ = 1 mInverse x y = (n * y + 1) `div` x where n = x - mInverse (y `mod` x) x -- just a quick way to test for primality n `divides` x = x `mod` n == 0 primes = 2:filter isPrime [3..] isPrime x = null . filter (`divides` x) $ takeWhile (\y -> y*y <= x) primes -- the property prop_rsa (p,q,x) = isPrime p && isPrime q && p /= q && x > 1 && x < n && rPrime e t ==> x == (x `powModN` e) `powModN` d where e = 3 n = p*q t = (p-1)*(q-1) d = mInverse e t a `powModN` b = modExp a b n (Thanks, google and random blog, for the implementation of modular multiplicative inverse) Question The problem should be obvious: there are way too many conditions on the property to make it at all usable. Trying to invoke quickCheck prop_rsa in ghci made my terminal hang. So I've poked around the QuickCheck manual a bit, and it says: Properties may take the form forAll <generator> $ \<pattern> -> <property> How do I make a <generator> for prime numbers? Or with the other constraints, so that quickCheck doesn't have to sift through a bunch of failed conditions? Any other general advice (especially regarding QuickCheck) is welcome.

    Read the article

  • Unsure of how to get the right evaluation order

    - by Matt Fenwick
    I'm not sure what the difference between these two pieces of code is (with respect to x), but the first one completes: $ foldr (\x y -> if x == 4 then x else x + y) 0 [1,2 .. ] 10 and the second one doesn't (at least in GHCi): $ foldr (\x (y, n) -> if x == 4 then (x, n) else (x + y, n + 1)) (0, 0) [1,2 .. ] ....... What am I doing wrong that prevents the second example from completing when it hits x == 4, as in the first one? I've tried adding bang-patterns to both the x and to the x == 4 (inside a let) but neither seems to make a difference.

    Read the article

  • Weirdness with cabal, HTF, and HUnit assertions

    - by rampion
    So I'm trying to use HTF to run some HUnit-style assertions % cat tests/TestDemo.hs {-# OPTIONS_GHC -Wall -F -pgmF htfpp #-} module Main where import Test.Framework import Test.HUnit.Base ((@?=)) import System.Environment (getArgs) -- just run some tests main :: IO () main = getArgs >>= flip runTestWithArgs Main.allHTFTests -- all these tests should fail test_fail_int1 :: Assertion test_fail_int1 = (0::Int) @?= (1::Int) test_fail_bool1 :: Assertion test_fail_bool1 = True @?= False test_fail_string1 :: Assertion test_fail_string1 = "0" @?= "1" test_fail_int2 :: Assertion test_fail_int2 = [0::Int] @?= [1::Int] test_fail_string2 :: Assertion test_fail_string2 = "true" @?= "false" test_fail_bool2 :: Assertion test_fail_bool2 = [True] @?= [False] And when I use ghc --make, it seems to work correctly. % ghc --make tests/TestDemo.hs [1 of 1] Compiling Main ( tests/TestDemo.hs, tests/TestDemo.o ) Linking tests/TestDemo ... % tests/TestDemoA ... * Tests: 6 * Passed: 0 * Failures: 6 * Errors: 0 Failures: * Main:fail_int1 (tests/TestDemo.hs:9) * Main:fail_bool1 (tests/TestDemo.hs:12) * Main:fail_string1 (tests/TestDemo.hs:15) * Main:fail_int2 (tests/TestDemo.hs:19) * Main:fail_string2 (tests/TestDemo.hs:22) * Main:fail_bool2 (tests/TestDemo.hs:25) But when I use cabal to build it, not all the tests that should fail, fail. % cat Demo.cabal ... executable test-demo build-depends: base >= 4, HUnit, HTF main-is: TestDemo.hs hs-source-dirs: tests % cabal configure Resolving dependencies... Configuring Demo-0.0.0... % cabal build Preprocessing executables for Demo-0.0.0... Building Demo-0.0.0... [1 of 1] Compiling Main ( tests/TestDemo.hs, dist/build/test-demo/test-demo-tmp/Main.o ) Linking dist/build/test-demo/test-demo ... % dist/build/test-demo/test-demo ... * Tests: 6 * Passed: 3 * Failures: 3 * Errors: 0 Failures: * Main:fail_int2 (tests/TestDemo.hs:23) * Main:fail_string2 (tests/TestDemo.hs:26) * Main:fail_bool2 (tests/TestDemo.hs:29) What's going wrong and how can I fix it?

    Read the article

  • Complete Haskore example

    - by Bill
    Does anyone know of a complete Haskore example that will take a small example and output a MIDI file? I'm looking for a starting point to start using Haskore and Google isn't turning up much. Thanks!

    Read the article

  • Why this Either-monad code does not type check?

    - by pf_miles
    instance Monad (Either a) where return = Left fail = Right Left x >>= f = f x Right x >>= _ = Right x this code frag in 'baby.hs' caused the horrible compilation error: Prelude> :l baby [1 of 1] Compiling Main ( baby.hs, interpreted ) baby.hs:2:18: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `return' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the expression: Left In the definition of `return': return = Left In the instance declaration for `Monad (Either a)' baby.hs:3:16: Couldn't match expected type `[Char]' against inferred type `a1' `a1' is a rigid type variable bound by the type signature for `fail' at <no location info> Expected type: String Inferred type: a1 In the expression: Right In the definition of `fail': fail = Right baby.hs:4:26: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `f', namely `x' In the expression: f x In the definition of `>>=': Left x >>= f = f x baby.hs:5:31: Couldn't match expected type `b' against inferred type `a' `b' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `Right', namely `x' In the expression: Right x In the definition of `>>=': Right x >>= _ = Right x Failed, modules loaded: none. why this happen? and how could I make this code compile ? thanks for any help~

    Read the article

  • When should I use $ (and can it always be replaced with parentheses)?

    - by J Cooper
    From what I'm reading, $ is described as "applies a function to its arguments." However, it doesn't seem to work quite like (apply ...) in Lisp, because it's a binary operator, so really the only thing it looks like it does is help to avoid parentheses sometimes, like foo $ bar quux instead of foo (bar quux). Am I understanding it right? Is the latter form considered "bad style"?

    Read the article

  • Asymptotic runtime of list-to-tree function

    - by Deestan
    I have a merge function which takes time O(log n) to combine two trees into one, and a listToTree function which converts an initial list of elements to singleton trees and repeatedly calls merge on each successive pair of trees until only one tree remains. Function signatures and relevant implementations are as follows: merge :: Tree a -> Tree a -> Tree a --// O(log n) where n is size of input trees singleton :: a -> Tree a --// O(1) empty :: Tree a --// O(1) listToTree :: [a] -> Tree a --// Supposedly O(n) listToTree = listToTreeR . (map singleton) listToTreeR :: [Tree a] -> Tree a listToTreeR [] = empty listToTreeR (x:[]) = x listToTreeR xs = listToTreeR (mergePairs xs) mergePairs :: [Tree a] -> [Tree a] mergePairs [] = [] mergePairs (x:[]) = [x] mergePairs (x:y:xs) = merge x y : mergePairs xs This is a slightly simplified version of exercise 3.3 in Purely Functional Data Structures by Chris Okasaki. According to the exercise, I shall now show that listToTree takes O(n) time. Which I can't. :-( There are trivially ceil(log n) recursive calls to listToTreeR, meaning ceil(log n) calls to mergePairs. The running time of mergePairs is dependent on the length of the list, and the sizes of the trees. The length of the list is 2^h-1, and the sizes of the trees are log(n/(2^h)), where h=log n is the first recursive step, and h=1 is the last recursive step. Each call to mergePairs thus takes time (2^h-1) * log(n/(2^h)) I'm having trouble taking this analysis any further. Can anyone give me a hint in the right direction?

    Read the article

  • Is do-notation specific to "base:GHC.Base.Monad"?

    - by yairchu
    The idea that the standard Monad class is flawed and that it should actually extend Functor or Pointed is floating around. I'm not necessarily claiming that it is the right thing to do, but suppose that one was trying to do it: import Prelude hiding (Monad(..)) class Functor m => Monad m where return :: a -> m a join :: m (m a) -> m a join = (>>= id) (>>=) :: m a -> (a -> m b) -> m b a >>= t = join (fmap t a) (>>) :: m a -> m b -> m b a >> b = a >>= const b So far so good, but then when trying to use do-notation: whileM :: Monad m => m Bool -> m () whileM iteration = do done <- iteration if done then return () else whileM iteration The compiler complains: Could not deduce (base:GHC.Base.Monad m) from the context (Monad m) Question: Does do-notation work only for base:GHC.Base.Monad? Is there a way to make it work with an alternative Monad class? Extra context: What I really want to do is replace base:Control.Arrow.Arrow with a "generalized" Arrow class: {-# LANGUAGE TypeFamilies #-} class Category a => Arrow a where type Pair a :: * -> * -> * arr :: (b -> c) -> a b c first :: a b c -> a (Pair a b d) (Pair a c d) second :: a b c -> a (Pair a d b) (Pair a d c) (***) :: a b c -> a b' c' -> a (Pair a b b') (Pair a c c') (&&&) :: a b c -> a b c' -> a b (Pair a c c') And then use the Arrow's proc-notation with my Arrow class, but that fails like in the example above of do-notation and Monad. I'll use mostly Either as my pair type constructor and not the (,) type constructor as with the current Arrow class. This might allow to make the code of my toy RTS game (cabal install DefendTheKind) much prettier.

    Read the article

  • wxHaskell on OS X

    - by Bill
    I want to use wxHaskell on OS X (Snow Leopard, MacBook Pro). I was able to install the library successfully and the script below: module Main where import Graphics.UI.WX main :: IO () main = start hello hello :: IO () hello = do f <- frame [text := "Hello!"] quit <- button f [text := "Quit", on command := close f] set f [layout := widget quit] does result in a window being displayed with a single button, as specified. However, nothing happens when I click the button - I don't even get the visual response of the button turning blue to indicate that it's been depressed (haha, no pun intended). I've heard that you have to run a package called "macosx-app" on wxHaskell binaries to get them to run, but I can't find this anywhere. It's not on my machine or (as far as I can tell) in the WX or wxHaskell distros. Anyone know what I need to do to get this to work?

    Read the article

  • Nested parsers in happy / infinite loop?

    - by McManiaC
    I'm trying to write a parser for a simple markup language with happy. Currently, I'm having some issues with infinit loops and nested elements. My markup language basicly consists of two elements, one for "normal" text and one for bold/emphasized text. data Markup = MarkupText String | MarkupEmph [Markup] For example, a text like Foo *bar* should get parsed as [MarkupText "Foo ", MarkupEmph [MarkupText "bar"]]. Lexing of that example works fine, but the parsing it results in an infinite loop - and I can't see why. This is my current approach: -- The main parser: Parsing a list of "Markup" Markups :: { [Markup] } : Markups Markup { $1 ++ [$2] } | Markup { [$1] } -- One single markup element Markup :: { Markup } : '*' Markups1 '*' { MarkupEmph $2 } | Markup1 { $1 } -- The nested list inside *..* Markups1 :: { [Markup] } : Markups1 Markup1 { $1 ++ [$2] } | Markup1 { [$1] } -- Markup which is always available: Markup1 :: { Markup } : String { MarkupText $1 } What's wrong with that approach? How could the be resolved? Update: Sorry. Lexing wasn't working as expected. The infinit loop was inside the lexer. Sorry. :) Update 2: On request, I'm using this as lexer: lexer :: String -> [Token] lexer [] = [] lexer str@(c:cs) | c == '*' = TokenSymbol "*" : lexer cs -- ...more rules... | otherwise = TokenString val : lexer rest where (val, rest) = span isValidChar str isValidChar = (/= '*') The infinit recursion occured because I had lexer str instead of lexer cs in that first rule for '*'. Didn't see it because my actual code was a bit more complex. :)

    Read the article

  • Weird cabal error: "inappropriate type"

    - by Bill
    ~ % cabal install --reinstall time Resolving dependencies... [1 of 1] Compiling Main ( /var/folders/0D/0D3du+YyGzuRETgUJZ5m8U+++TI/-Tmp-/time-1.2.0.251774/time-1.2.0.2/Setup.hs, /var/folders/0D/0D3du+YyGzuRETgUJZ5m8U+++TI/-Tmp-/time-1.2.0.251774/time-1.2.0.2/dist/setup/Main.o ) Linking /var/folders/0D/0D3du+YyGzuRETgUJZ5m8U+++TI/-Tmp-/time-1.2.0.251774/time-1.2.0.2/dist/setup/setup ... Configuring time-1.2.0.2... setup: dist/setup-config51799.tmp: inappropriate type cabal: Error: some packages failed to install: time-1.2.0.2 failed during the configure step. The exception was: ExitFailure 1 ~ % Has anyone seen this before?

    Read the article

  • How to redirect within a monad in Yesod?

    - by Squazic
    I'm currently using the fb package to write a Yesod app that takes data from Facebook. In my Handler, I've managed to get the first step of the authentication to work, but I need to redirect to the url that getUserAccessTokenStep1 returns, which I've defined as fbRedirUrl. I'm having trouble with all the monad wrapping and type checking to make sure I can redirect to this url. getAccessTokenR :: Handler RepHtml getAccessTokenR = do withManager $ \manager -> do FB.runFacebookT creds manager $ do fbRedirUrl <- FB.getUserAccessTokenStep1 redirUrl [] liftIO $ print fbRedirUrl

    Read the article

  • Better exception for non-exhaustive patterns in case

    - by toofarsideways
    Is there a way to get GHCi to produce better exception messages when it finds at runtime that a call has produced value that does not match the function's pattern matching? It currently gives the line numbers of the function which produced the non-exhaustive pattern match which though helpful at times does require a round of debugging which at times I feel is doing the same set of things over and over. So before I tried to put together a solution I wanted to see if something else exists. An exception message that in addition to giving the line numbers shows what kind of call it attempted to make? Is this even possible?

    Read the article

  • Are monads Writer m and Either e categorically dual?

    - by sdcvvc
    I noticed there is a dual relation between Writer m and Either e monads. If m is a monoid, then unit :: () -> m join :: (m,m) -> m can be used to form a monad: return is composition: a -> ((),a) -> (m,a) join is composition: (m,(m,a)) -> ((m,m),a) -> (m,a) The dual of () is Void (empty type), the dual of product is coproduct. Every type e can be given "comonoid" structure: unit :: Void -> e join :: Either e e -> e in the obvious way. Now, return is composition: a -> Either Void a -> Either e a join is composition: Either e (Either e a) -> Either (Either e e) a -> Either e a and this is the Either e monad. The arrows follow exactly the same pattern. Question: Is it possible to write a single generic code that will be able to perform both as Either e and as Writer m depending on the monoid given?

    Read the article

  • Safe and polymorphic toEnum

    - by jetxee
    I'd like to write a safe version of toEnum: safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t A naive implementation: safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t safeToEnum i = if (i >= fromEnum (minBound :: t)) && (i <= fromEnum (maxBound :: t)) then Just . toEnum $ i else Nothing main = do print $ (safeToEnum 1 :: Maybe Bool) print $ (safeToEnum 2 :: Maybe Bool) And it doesn't work: safeToEnum.hs:3:21: Could not deduce (Bounded t1) from the context () arising from a use of `minBound' at safeToEnum.hs:3:21-28 Possible fix: add (Bounded t1) to the context of an expression type signature In the first argument of `fromEnum', namely `(minBound :: t)' In the second argument of `(>=)', namely `fromEnum (minBound :: t)' In the first argument of `(&&)', namely `(i >= fromEnum (minBound :: t))' safeToEnum.hs:3:56: Could not deduce (Bounded t1) from the context () arising from a use of `maxBound' at safeToEnum.hs:3:56-63 Possible fix: add (Bounded t1) to the context of an expression type signature In the first argument of `fromEnum', namely `(maxBound :: t)' In the second argument of `(<=)', namely `fromEnum (maxBound :: t)' In the second argument of `(&&)', namely `(i <= fromEnum (maxBound :: t))' As well as I understand the message, the compiler does not recognize that minBound and maxBound should produce exactly the same type as in the result type of safeToEnum inspite of the explicit type declaration (:: t). Any idea how to fix it?

    Read the article

  • problem with Double and Rational Number

    - by altair211
    Hi, I am writing a function in which I need to read a string contains floating point number and turn it back to Rational. But When I do toRational (read input :: Double), it will not turn for eg: 0.9 into 9 % 10 as expected, but instead 81..... % 9007... Thx

    Read the article

  • Applying a function to an arbitrarily long list of arguments

    - by alphomega
    I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers, and returns the result of the function (Where each integer in the list is an argument in order. I was thinking something like: apply :: ([Int] -> Int) -> [Int] -> Int apply f x:xs = apply (f x) xs apply f [] = f But I know this won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes some amount of int arguments. Additionally, when I get to the base case the f argument to apply should actually be an integer, violating the type signature anyway. Does anyone know how to deal with this sort of problem?

    Read the article

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