spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » HASKELL » Page 1
How does the following code go through a text file?
The handle that openFile returns is associated with a pointer to the current position in the file. From the docs: Most handles will also have a current I/O position indicating where the next input or output operation will occur. Whenever you read a line from that handle via hGetLine this pointer will be advanced to the next line. IIRC that is the same behavior as with C file-handles.

Categories : Haskell

cabal install cabal-install errors out on linux
This issue is because of an old version of ghc-7.0.4.I downloaded ghc 7.8.3 source tarball from here and installed it. Then ghc 7.8.3 had old version of cabal so, have to unregister it from ghc 7.8.3 using ghc unregister Cabal . Then run bootstrap.sh from cabal-install-1.20 folder and got cabal-install 1.20 successfully.

Categories : Haskell

Empty list vs Maybe to represent failed computation in Haskell
However it seems that a list can model everything a Maybe can model and more The "and more" is an excellent reason to use Maybe. As a consumer of a list, you need to be able to handle zero, one or multiple values. As a consumer of a Maybe, you only need to be able to handle zero or one values. So in cases where multiple values don't make sense, it is much better to use Maybe so that you know

Categories : Haskell

How to select from table ordering by primary key
That should actually work; EntryId is both a type and data constructor. For example, the following code (just tweaked from the synopsis of the persistent chapter of the Yesod book) compiles just fine: {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiPara

Categories : Haskell

Circular Typing with Constraints
I suppose the problem is that foos return value isn't actually polymorphic. foo itself is polymorphic but the returned value must exist at a specific type. Unfortunately, the type you want to use isn't available yet and cannot be brought into scope at foos call site because of the circular reference. If we write out the definition of foo in pseudo-core, the problem is clear: foo (@ iType) _ = (

Categories : Haskell

Constructing minimal Haskell example on error-handling in the State Monad
The type I would recommend using is: StateT [Int] Maybe Int A really simple way to use Maybe/MaybeT is to just call mzero whenever you want to fail and mplus whenever you want to recover from a failed computation. This works even if they are layered within other monad transformers. Here's an example: addState' :: StateT [Int] Maybe Int addState' = do ms <- get case ms of [] -&

Categories : Haskell

Searching a List of a List with List
You problem is here: ... | elem x y = x : search' x ys | otherwise = search' xs ys In the first case you are calling search' with x and in the second case with xs. But x and xs have different types - xsis a list of x. You need to structure the iteration like this: search :: Eq a => [a] -> [[a]] -> [[a]] search [] _ = [] search (x:xs) ys = (go x ys) ++ search xs ys where go is

Categories : Haskell

Haskell type operator precedence
Here are the relevant bits of the GHC sources in compiler/basicTypes/BasicTypes.lhs: maxPrecedence, minPrecedence :: Int maxPrecedence = 9 minPrecedence = 0 defaultFixity :: Fixity defaultFixity = Fixity maxPrecedence InfixL negateFixity, funTyFixity :: Fixity -- Wired-in fixities negateFixity = Fixity 6 InfixL -- Fixity of unary negate funTyFixity = Fixity 0 InfixR -- Fixity of '->' So t

Categories : Haskell

Convert a [String] list to a [Double] list in Haskell
You're right - read x :: Double is of type Double, while the return type of the function is of type [Double] (meaning "a list of Double"). Something like this: stringToDouble [x] = [read x :: Double] should work. Note that if you're trying to convert each element of the list independently, then you should write your function using map instead of using explicit recursion. If f is of type Strin

Categories : Haskell

What exactly is the kind "*" in Haskell?
First off, * is not a wildcard! It's also typically pronounced "star." Bleeding edge note: There is as of Feb. 2015 a proposal to simplify GHC's subkind system (in 7.12 or later). That page contains a good discussion of the GHC 7.8/7.10 story. Looking forward, GHC may drop the distinction between types and kinds, with * :: *. See Weirich, Hsu, and Eisenberg, System FC with Explicit Kind Equality.

Categories : Haskell

QuickCheck Tests for Custom Type
1 & 2. You can either: define an Arbitrary instance or create a Gen ... function and use something like the forAll combinator. See this answer for an example of using forAll with a Gen ... function. The signature of second_functor_law_int is: second_functor_law :: (Int -> Int) -> (Int -> Int) -> Cons Int -> Bool so by running quickCheck second_functor_law_int you are asking QuickCheck to

Categories : Haskell

Haskell - Comparing different items with one another within a list
My understanding is that a list of commands represents a sequence which depends on each previous command to be valid or invalid. That is, [Add "Bob", Allow "Bob" ...] is valid, while [Allow "Bob" ..., Add "Bob"]. In this case, the simplest way to do this is probably to reverse the list, and iterate through it; if you find an Allow, insert it into the set of Adds which you must find; if you find a

Categories : Haskell

Haskell : continue program execution
A basic input loop: loop = do putStr "Enter a command: " input <- getLine let ws = words input -- split into words case ws of ("end":_) -> return () ("add":xs:ys:_) -> do let x = read xs :: Int y = read ys print $ x + y loop ... other commands ... _ -> do putStrLn "command n

Categories : Haskell

Algebraic Data Types and Equality
It says you need to add the constraint to prop_id_functor_law, so it'd be prop_id_functor_law :: Eq a => Cons a -> Bool. The deriving part just means it derives the instance instance Eq a => Eq (Cons a) where Empty == Empty = True Cons a1 x1 == Cons a2 x2 = a1 == a2 && x1 == x2 _ == _ = False You still have that the type parameter is constrained in order for the Eq

Categories : Haskell

Short-circuit AND within IO Monad
The operation you want is simple to define explicitly. shortCircuitAnd :: Monad m => m Bool -> m Bool -> m Bool shortCircuitAnd x y = do r1 <- x -- perform effect of x if r1 then y -- perform effect of y and return result else return False -- do *not* evaluate or perform effect of y Of course, you can use this function infix as well, using backticks: x `shortCircu

Categories : Haskell

Recursion on a list of tuples
This modification of your code will type check: -- lookUp :: we'll have GHC tell us the type signature lookUp a [] = [] lookUp a ((x,y):pairs) | a == x = y : lookUp a pairs | otherwise = x : y : lookUp a pairs Some obvious mistakes: When you recursively call lookUp you only called it with one argument (you forgot the a argument) The pattern [(x,y),(xs,ys)] will only match a list of

Categories : Haskell

Speeding up binary tree traversal with multiple processors Haskell (parallel)
Your parallel countBoxes needs an NFData (Tree x) instance to use force on the Tree xs left and right. You can require that one exists by adding NFData x to the context for the type signature for countBoxes. -- Parallel function to count leaves in tree countBoxes :: NFData x => Tree x -> Int ... NFData x is enough to deduce NFData (Tree x) from due to your instance NFData a => NFData

Categories : Haskell

Restrictions on Types of `a -> b` Function
a and b must have kind *, that is they must not be type constructors that require arguments. So they could be Integer, (c -> d) or Maybe String, but not (->), (a ->) or Maybe. a can't be a function, i.e. (c -> d), can it? Yes, it can. It can be any possible type of kind *.

Categories : Haskell

How and why is [1 .. 0] different from [1 .. -1] in Haskell?
Did you try [1..(-1)]? In Haskell, you cannot write negative numbers like -1 directly. You need to put them in parentheses. The reason is that Haskell doesn't have prefix unary operators because operators in Haskell are always infix. Hence -1 is parsed as [operator (-)] [numeric 1] and not [numeric -1]. This is what causes the problem. To avoid this problem, negative numbers must always be put in

Categories : Haskell

Haskell Novice Trouble with Splitting a List in Half
The / is used for when you're happy to have a non-integer answer. Since you've already checked the number's even, you can hapily use integer division with div: halve :: [a] -> ([a], [a]) halve x | even len = (take half x, drop half x) | otherwise = error "Cannnot halve a list of odd length" where len = length x half = len `div` 2 (Personally I'd be happy to halve an o

Categories : Haskell

map and zip Tree in haskell
The difference between (Label -> Label) and Label on its own is that the former is a function that, given a Label, produces a new Label. As for your next question: In the first Tree datatype, a tree can indeed not be Null since your datatype definition doesn't allow for that. Other than that, you've tagged your question with the binary-tree tag, but the datatype you want to have clarified isn'

Categories : Haskell

Haskell pattern matching do expression compiler warning
Use a case expression instead: do case "" of [] -> undefined -- or whatever else you want to do (x:xs) -> return x Hope that helps.

Categories : Haskell

Why can I not make a (Functor f) => ConcreteType -> f String into an instance Functor ((->) ConcreteType)?
Consider the definition of Functor: class Functor f where fmap :: (a -> b) -> f a -> f b The class or the method doesn't constrain the types a and b, so any fmap you define must be applicable to any types a and b. You could define your own type class, e.g.: class MyFunctor f where myfmap :: (String -> String) -> f String -> f String but that wouldn't be Functor.

Categories : Haskell

Generic typealias in Swift
typealias cannot currently be used with generics. Your best option might be to wrap the parser function inside a struct. struct Parser<A> { let f: String -> [(A, String)] } You can then use the trailing closure syntax when creating a parser, e.g. let parser = Parser<Character> { string in return [head(string), tail(string)] }

Categories : Haskell

Separating input string and call the required function using case statement
First import Data.List, which has all the list manipulation functions. Then to split at the first space, use span. Then drop the first element of the second half of the list, since that will be the space. The code is then: import Data.List f :: String -> (String, String) f s = (func, tail args) where (func, args) = span (/=' ') s EDIT: Oh yeah, for the second part of your question. You're

Categories : Haskell

Non-exhaustive pattern in function declaration
You need to complete the pattern match for novaCoord _ [] _, you need an otherwise clause in your guard for novaCoord, and you missed the case for converte [x] in the where clause for novaCoord.

Categories : Haskell

Tricky list transformation in Haskell
If you want super simple, and if this isn't part of a larger pattern (ie- you need this to work for NxN matrices), just do this. f [x1,x2,x3,x3,x4,x5,x6,x7,x8,x9,x10, x11,x12,x13,x14,x15,x16,x17,x18,x19,x20, x21,x22,x23,x24,x25,x26,x27] = [[x1,x4,x7],[x2,x5,x8],[x3,x6,x9] ,[x10,x13,x16],[x11,x14,x17],[x12,x16,x18] ,[x19,x22,x25],[x20,x23,x26],[x21,x24,x27]]

Categories : Haskell

Haskell apply single value to a list of functions
If flist is the list of functions and x is the argument, you need map (f -> f x) flist. For example Prelude> map (f -> f 10) [(4 +), (3 *)] [14,30]

Categories : Haskell

Not using a correct syntax to call function in main
the var <- computation syntax is for monadic values (inside a do block) like getLine. In your case you have a pure computation so you can use let just like you would do in GHCi: main :: IO() main = do let result = charName 'a` putStr result

Categories : Haskell

Does GHCi not apply the default declaration to resolve type ambiguity?
Does ghci not apply the default declaration to resolve type ambiguity? In GHC 7.8 or greater the Monomorphism Restriction is indeed off inside the GHCi shell, so declarations at the interactive shell will not apply the Num defaulting rules to top level expressions not under a lambda binder ( per the monomorphism restriction ). The monomorphism restriction will still apply to external modules

Categories : Haskell

Haskell Help -- Calculating Mean of A List
You are using fromInt that doesn't exist and that's the error. For a short solution to the problem go to the end of this. Let me start by saying that the reason why you need that fromInt (or a replacer, considering that's wrong) is because the / function exists on Fractional types. You can see it on GHCI: Prelude> :t (/) (/) :: Fractional a => a -> a -> a Prelude> :t length lengt

Categories : Haskell

Haskell - Type error in application: Type does not match
Perhaps your confusion is here: data Expr = ... | Expr String This does not mean that every Expr can be converted to a string. It just means that there is a function called Expr which takes a String and returns an Expr (the type). The obvious way to define parseExpr for the Pred case is to call parseExpr on the elements of the Expr list, e.g.: parseExpr (Pred p exprs) = let strs = map pa

Categories : Haskell

How can I specialize a type in a Frege QuickCheck?
It is unfortunately the case that the where types = xs :: [Int] gets removed by the let expression simplification and canonicalization pass, which comes before type checking even. This is, so to speak, a side effect of dependency analysis, where it is seen that types is totally useless. You can write: p_rev = property rev where rev (xs::[Int]) = (reverse . reverse) xs == xs or even:

Categories : Haskell

Haskell - Implementing Monoid what happens if the operator is not associative
Nothing bad would happen in terms of type safety: Your programs will still not crash. But a data structure relying on your Monoid instance might give unexpected or wrong results. Consider a tree that is re-balanced upon insertion, and that provides a way to combine its elements using their Monoid instance. Then the re-balancing, which is supposed to be an internal operation and not visible to yo

Categories : Haskell

haskell join multi-level monad
If you note that m (n _) is a monad transformer then you can define this operation. This is certainly the case when we notice that IO (Maybe a) is the same as MaybeT IO a: we then just use MaybeT's join. We can do this in no small part due to the fact that Maybe and IO "layer" especially nicely. On the other hand, not all "composed" monads are monad transformers. In particular, IO [a] isn't reall

Categories : Haskell

General 'typeless' STack in Haskell
You shouldn't be able to define pop on the empty tuple, but the rest is smooth enough if we use a type class to represent cases on the type of the stack. class Stack h where push :: a -> h x -> h (a, x) pop :: h (a, x) -> (h x, a) top :: h (a, x) -> (h (a, x), a) top hax = let (_, a) = pop hax in (hax, a) newtype S x = S x instance Stack S where push a (S x) = S (a, x) p

Categories : Haskell

Accumulator in foldr
Consider the evaluation of a simple foldr expression based on the (correct) definition you provided: foldr (+) 0 [1,2,3,4] = 1 + foldr (+) 0 [2,3,4] = 1 + 2 + foldr (+) 0 [3,4] = 1 + 2 + 3 + foldr (+) 0 [4] = 1 + 2 + 3 + 4 + foldr (+) 0 [] = 1 + 2 + 3 + 4 + 0 = 10 So you are right: acc doesn't really "accumulate" anything. It never takes on a value other than 0. Why is it called "acc" if it

Categories : Haskell

Quickcheck, defining Arbitrary instances using a function whose result depends on its arguments
Use the forAll combinator which has the signature: forAll :: (Show a, Testable prop) => Gen a -> (a -> prop) -> Property A quick example: import Test.QuickCheck genA :: Gen Int genA = choose (-100,100) genB :: Gen Int genB = choose (1,100) prop_example :: Int -> Bool prop_example n = n > 0 testA = quickCheck $ forAll genA prop_example testB = quickCheck $ forAll genB prop

Categories : Haskell

Compare two lists and return the first element that is in both lists
It's not clear, if they should be at the same position or what. Assuming yes: f = ((head . concat) .) . zipWith (x y -> [x | x == y]) Or, expanded: f xs ys = head $ concat $ zipWith (x y -> [x | x == y]) xs ys If an index must be minimal in the first list: f xs ys = head [x | x <- xs, x `elem` ys]

Categories : Haskell


Recently Add
Haskell, How to define mean by recursion, median and variance?
How does the following code go through a text file?
cabal install cabal-install errors out on linux
Empty list vs Maybe to represent failed computation in Haskell
How to select from table ordering by primary key
Circular Typing with Constraints
Constructing minimal Haskell example on error-handling in the State Monad
Searching a List of a List with List
Haskell type operator precedence
Convert a [String] list to a [Double] list in Haskell
What exactly is the kind "*" in Haskell?
QuickCheck Tests for Custom Type
Haskell - Comparing different items with one another within a list
Haskell : continue program execution
Algebraic Data Types and Equality
Short-circuit AND within IO Monad
Recursion on a list of tuples
Speeding up binary tree traversal with multiple processors Haskell (parallel)
Restrictions on Types of `a -> b` Function
How and why is [1 .. 0] different from [1 .. -1] in Haskell?
Haskell Novice Trouble with Splitting a List in Half
map and zip Tree in haskell
Haskell pattern matching do expression compiler warning
Why can I not make a (Functor f) => ConcreteType -> f String into an instance Functor ((->) ConcreteType)?
Generic typealias in Swift
Separating input string and call the required function using case statement
Non-exhaustive pattern in function declaration
Tricky list transformation in Haskell
Haskell apply single value to a list of functions
Not using a correct syntax to call function in main
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.