You can certainly do this without changing the type signature of func :: [Int] -> [Int]: have func call a different function, which takes an extra argument that is the counter you were talking about: func :: [Int] -> [Int] func = go 0 where go _ [] = []...
Tying the not like that doesn't appear to increase sharing. Contrast with: cycle xs = let x = xs ++ x in x Tying the knot here has the effect of creating a circular linked list in memory. x is its own tail. There's a real gain. Your suggested implementation...
haskell,template-haskell,deriving
The paper Invertible Syntax Descriptions: Unifying Parsing and Pretty Printing describes one particularly idiomatic solution. Your example looks like this, using the invertible-syntax package based on that paper: import Prelude hiding (Applicative(..), print) import Data.Maybe (fromJust) import Text.Syntax import Text.Syntax.Parser.Naive import Text.Syntax.Printer.Naive data TVShow = BobsBurgers | MrRobot | BatmanTAS...
The other answers are quite nice in that they present a single (parameterized) data type that can handle structures of any depth; however, they use advanced type system features to achieve this. On the other hand, there are quite simple features that can be used instead to achieve the same...
Let's rewrite this: l = [l1, l2, l3] where l1 = [] l2 = [[]] l3 = [[[]]] Now we assign type variables: ab initio l1 :: b l2 :: b l3 :: b since they all have to have the same type, so l has some type [b]. Now,...
This is a partial answer, written for Scala but applicable to other languages. A bug is something happening which was not expected. Thus, to solve bugs, the language should allow to let the user write any expectations and interact with them (proof, synthesis, etc.). There are several ways to address...
It depends on what you mean by being able to plug in "any game". Is every game going to have a MoveTag denoting whose turn it is? If so, then you can give g a kind signature and define the type class as class Minimaxable (g :: MoveTag -> *)...
It's been a while since I worked on the code, so don't take this as authoratative (like Daniel mentioned, -ddump-simpl is a good call here). But I don't believe we're using the blaze-html combinators, just the data type. Hamlet itself concatenates strings as much as possible at compile time to...
It seems odd to me to be using STM and semaphores in the same code block... Why not do the entire thing in STM? In particular, why not a TChan (Maybe x), with Nothing indicating the end of the sequence? Also, notice that your fstPipe likely just generates a bunch...
It's a parenthesization error: compress x newMap (i+1) "" out++[(newMap Map.! c, s)] parses as (compress x newMap (i+1) "" out) ++ [(newMap Map.! c, s)] But you wanted compress x newMap (i+1) "" (out++[(newMap Map.! c, s)]) Fun problem, by the way. I tried rewriting your code to make...
This looks like a special case of a (jargon here but it can help with googling) paramorphism, a generalisation of primitive recursion to all initial algebras. Reimplementing ListCase Let's have a look at how to reimplement your function using such a combinator. First we define the notion of paramorphism: a...
Well, foo (x:y:z:xs) plus a “too short clause” certainly wouldn't be a bad solution. Another would be foo xs = case splitAt 3 xs of ([x,y,z],xs') -> calc x y z : foo (y:z:xs') _ -> [] Or, perhaps nicest, import Data.List (tails) foo xs = [ calc x y...
sockets,haskell,network-programming,io-monad
The idiomatic way to repeat the same action over and over again forever is forever serverLoop :: Socket -> IO () serverLoop sock = forever $ do (conn, _) <- accept sock forkIO $ handleConn conn ...
You can place a newline anywhere between lexical tokens of an expression. However, there are constraints about how much indentation may follow the newline. The easy rule of thumb is to indent the next line to start to the right of the line containing the expression. Beyond that, some style...
haskell,type-level-computation,hlist
Answering your comment: Actually, I can do if I can filter the heterogeneous list by type. Is that possible? You can filter the heterogeneous list by type if you add a Typeable constraint to b. The main idea is we will use Data.Typeable's cast :: (Typeable a, Typeable b) =>...
haskell,unique,predicate,quickcheck
Definitely you want the instance to produce only instances that match the intention of the data type. If you want all the variables to be distinct, the Arbitrary instance must reflect this. (Another question is if in this case it wouldn't make more sense to define Vars as a set,...
First of all, there is a regression in Threepenny 0.6 which affects the code we are writing here. For the moment, if you are using 0.6 you will have either to go back to 0.5 or to cabal unpack and apply the temporary fix Heinrich suggests in the issue linked...
> :t zipWith zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] > zipWith (*) [1,2,3] [4,5,6] [4,10,18] It's the eighth result provided by Hoogle when queried with your type (a -> a -> a) -> [a] -> [a] -> [a] Moreover, when you need to...
class,haskell,opengl,types,uniform
Try adding -XFlexibleContexts and the constraint, literally, to your existing answer: {-# LANGUAGE FlexibleContexts #-} mvpUnif :: ( GL.UniformComponent a , Num a , Epsilon a , Floating a , AsUniform a , AsUniform (V4 (V4 a)) ) => (GLState a) -> ShaderProgram -> IO () Usually this is the...
You can define this as follows: f 0 = 1 f i | even i = sin(k) * cos(k) | otherwise = cos(k/2) - tan(2*k) where k = fromIntegral $ div i 2 I replaced x by f because x looks more like a variable than a function. Furthermore I...
createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = Item $ do putWord8 3 putWord16be 4 putWord32be identifier or createNotificationIdentifierItem :: APNSIdentifier -> APNSItem createNotificationIdentifierItem (Identifier identifier) = do Item $ putWord8 3 Item $ putWord16be 4 Item $ putWord32be identifier after making APNSItem an instance of Monad (you can...
Your first point-free attempts don't work because . composes functions with one argument, while take takes two. What really happens is that code like decrease_first = map (subtract1) . take is equivalent to decrease_first n = map (subtract1) (take n) but now take n is not a list, hence a...
haskell,types,binding,dependent-type
The type you suggest can not be implemented, i.e. it is not inhabited: takeWhileVector :: (a -> Bool) -> Vector a n -> Vector a m Remember that the caller chooses the type variables a,n,m. This means that the caller can use your function as e.g. takeWhileVector :: (a ->...
The code you posted desugars into the following. x >>= (\a -> print a >> return 500) Or, expanding out the definition of (>>) x >>= (\a -> print a >>= (\_ -> return 500)) Then, you can see that in the different calls to (>>=), the types a and...
First, module Tree2 ( Tree ) where only exports the Tree data type, not its constructors; you should use module Tree2 ( Tree(..) ) where instead. Second, as you're doing a qualified import, you need to use Tree2.EmptyTree instead of just EmptyTree....
haskell,syntax,infix-notation,applicative,infix-operator
Why is f <$> g <$> x equivalent to (f . g) <$> x ...well, this isn't so much a functor-thing as a Haskell-thing. The reason it works is that functions are functors. Both <$> operators work in different functors! f <$> g is in fact the same as...
I am not ready to give a nice list of best practises, but for starters if you want to keep stuff sanely organized, use explicit exports instead of just exporting everything, e.g: module Parser ( parseConfig ) where ... Explicit exports also allow you to reexport your imports, e.g. module...
As Conor states, this is not directly possible. You can, however, define data K a = ... | C a Then this promotes to C :: a -> K a If you then use K *, you can achieve what you want. ...
using TypeFamilies The problem is that you somehow have to connect b with your collection (the elements in it) - there are several ways to do this but I think a rather nice one is using TypeFamilies: {-# LANGUAGE TypeFamilies #-} module Test where import qualified Data.Map as Map import...
Using multi-ghc-travis, you can also set up Travis-CI for ghc 7.10 (apart from other versions).
list,haskell,functional-programming,idiomatic
The multiple call to addPoints could be replaced by a fold. As suggested in a comment, reversing your addPoint function would make things easier: addPoint' :: Point -> Polyline -> Polyline addPoint' p line = p:line So then your constructLine function could build a temporary list of the points to...
You're making eval a bit too low-level. By including Literals in the signature. A better way to do this is, is using recursion: eval :: Expression -> Bool eval (Literal x) = x eval (Operation AND x y) = (eval x) && (eval y) eval (Operation OR x y) =...
<**> from Control.Applicative is flip <*>. Your example can work with that, slightly rearranged: >((+) <$> Just 3 <*> Just 5) <**> ((+) <$> Just 6) Just 14 ...
Consider the simpler problem of summing the first 100 positive integers: sum [x | x <- [1,2..], x <= 100] This doesn't work either. As a human, you know that once x <= 100 returns False, it will never return True again, because x is getting larger. But Haskell doesn't...
The getStdRandom function basically looks up a StdGen value in a global variable, runs some function on it, puts the new seed back into the global variable, and returns the result to the caller. If the function in question returns with an error, that error gets put into the global...
It is difficult for cabal-install to produce a complete description of the mutual incompatibilities of an installation problem. It instead decides to print the first path to failure. However, it prints Dependency tree exhaustively searched. which indicates that there actually is no solution to the given problem. One thing that...
haskell,concurrency,network-programming
Three days later and its solved: Was actually unrelated to either the networking or concurrency code, and infact caused by my incorrect re-implementation of Yampas dpSwitch in Netwire. Corrected code posted below for anyone wishing to implement this function: dpSwitch :: (Monoid e, Applicative m, Monad m, T.Traversable col) =>...
Try to write your last line as def map(tree:Tree[Int])(f:Int=>Int) : Tree[Int] = fold(tree , EmptyTree:Tree[Int])((l,x,r) => Node(f(x),l,r)) Scala's type inference is very limited compared to haskell, in this case it tries to infere type of fold from it's arguments left to right, and incorectly decides that result type of fold...
This is intentional: The UI.checkedChange event only triggers when the user clicks the checkbox, but not when it is set programmatically. The intention is that the bBool behavior represents the canonical state of the checkbox and the UI.checkedChange event represents request from the user to change it, which may or...
You need ScopedTypeVariables and forall introduction to get a scoped type variable: {-# LANGUAGE ScopedTypeVariables #-} bar :: forall a. Foo a => a -> Int bar _ = foo (Proxy :: Proxy a) ...
The read lambda applies to the first argument and the first argument to the function given to foldl is the accumulator. Those two arguments are the opposite for foldr. So, expanded, it looks like this: foldl (\acc element -> (read acc :: Int) + element) 0 ["10", "20", "30"] Since...
Depending on if consuming the whole input should be the property of parseNoteDocument or just the tests, I'd extend one or the other with endOfInput or atEnd. I'd suggest to define a proper Parser for your documents, like parseNoteDocument' :: Text -> Parsec NoteDocument parseNoteDocument' = many parseLine and then...
string,function,haskell,if-statement,recursion
Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...
haskell,lambda,instance,show,typeclass
Add an instance declaration for the Show class. instance Show LExpr where show = show' And remove the deriving(Show) part data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq) ...
linux,haskell,make,ghc,theorem-proving
Looks like paradox was written for a rather old version of GHC. You can fix all these "Could not find module" errors by using GHC version 7.8 or older and setting GHC = ghc -hide-package base -package haskell98 in the Makefile, though you will likely encounter more errors after that....
string,function,haskell,recursion,parameters
Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can...
For the Not in scope: data constructor 'Integer' part, the problem is that you have an extra Integer in the line isDigit c = TNumber Integer (read c) : tokenize cs which should be isDigit c = TNumber (read [c]) : tokenize cs The [c] part is needed because read...
length is O(1), so splitAt suffices to define everything you need, in an efficient way. splitAtR i s = splitAt (length s - i) s takeR i s = snd $ splitAtR i s dropR i s = fst $ splitAtR i s According to the docs, splitAt costs O(log(min(i,length...
You need explicit type annotations when GADTs are involved: abigail :: Person abigail = let x :: Person x Name = "Abigail" x Age = 27 in x Without it, GHC roughly sees let x Name = "Abigail" and says "OK, x is a function from the type of Name,...
Here's an example which uses random-fu: import Data.Random -- for randomness import Text.Printf -- for printf import Data.Foldable -- for the for_ loop -- pdf and cdf are basically “Distribution -> Double -> Double” main = do -- defining normal distribution with mean = 10 and variation = 2 let...
haskell,types,monoids,type-variables,foldable
I found that this typechecks: {-# LANGUAGE RankNTypes #-} module FoldableTA where import Control.Category import Prelude hiding (id, (.)) class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b d -> h b d foldrTA ::...
foldr :: (a -> b -> b) -> b -> [a] -> b as can be found on Hoogle expects a function of the form a -> b -> b, but your test function rather looks like a -> a -> b. As Carsten mentioned, the b of your function...
Simple decimal literals without type indicator (i.e. one of the letters lndf) do not automatically have type Int in Frege. They will get assigned the type you probably wanted, and the literal will get adapted accordingly. This is why they are called DWIM (do what I mean) literals. This is...
haskell,cabal,cabal-install,nix,haskell-ng
Could someone please explain what haskellng is in a simple, clear way? Well, haskellng is the next generation Nix Haskell package set made for Nix. I think most of the work was done by Peter Simons. But note that in the latest master version, haskellngPackages has been renamed back...
list,haskell,list-comprehension
The comprehension syntax is [ <expression> | ... ] For <expression> you have ([x,z], i:j:s, j), b which is syntactically wrong. Did you mean ([x,z], i:j:s, b)?...
A exitcode-stdio-1.0 test suite is only an executable, which needs to implement main :: IO(). Cabal test just runs the executable and captures the output in a log file. So if you use a test framework like tasty, you'll get the output the tasty way. Of course, you can just...
The problem is you are only considering the same pairs of element on each pass. Consider: swap (a:b:t) | a <= b = a : b : (swap t) swap (a:b:t) | b < a = b : a : (swap t) What if we have a list [4,1,1,1]? swap...
The key point here is that the annotation should be in a separate line. If we do that, then we have a binding with an explicit type, as far as GHC is concerned. someFunction :: MyMonad () someFunction = do ... let x :: Traversal' MyState MyDataT x = myState.clients.ix...
Your example is slow because it uses lazy IO with String-s. Both have their own overheads. In particular, String is a linked list of Char-s, therefore it has two words of space overhead for each character (one word for the constructor tag and one for the forward pointer), and each...
valueKind :: SomeValue a -> SomeKind is not possible. The a type parameter isn't present runtime in any shape or form, so we can't branch on it. The standard method for making use of types both at runtime and compile time is to make so-called singleton types. Singletons are indexed...
take is of type Int -> [a] -> [a], i.e. it returns a list. It seems you’re looking for head, which returns one element. head $ head $ repeat [1..] ...
function,haskell,infix-notation
Not really, no. On the other hand, you could perfectly well define a different operation that provides the default argument, e.g. withDef data2 = {- your default value -} <*> data2 If you really want to use a name that would otherwise be an operator, you can still name this...
haskell,compiler-errors,instance,equality,typeclass
It isn't clear what you are trying to achieve. Here are some thoughts: When you declare an instance of a class like instance (Eq a) => PartOrd a, you are expected to provide implementations for the functions in PartOrd a (ie partcmp, not == and \=). The compiler is telling...
You may write: main = readLn >>= print . subsequences You will need to nail down the type to be read, for example by having a monomorphic subsequences or by annotating readLn. In ghci: Data.List> (readLn :: IO [Integer]) >>= print . subsequences [1,2,3] [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] (I typed in the first...
Network.HTTP.Conduit and Network.HTTP.Headers are from incompatible HTTP libraries. Request headers for http-conduit/http-client can be created using the http-types library: import Data.Aeson import qualified Data.ByteString.Lazy as B import Network.HTTP.Conduit as HHeaders import qualified Network.HTTP.Types as HTypes import qualified Data.ByteString.Char8 as C8 import qualified Data.ByteString.Lazy.Char8 as LC8 myHeader1 = (HTypes.hAccept, C8.pack "some...
Instances are only matched by the instance head. So, for the purpose of overlapping or not, what you wrote is no better than instance ToAVector [] a instance ToAVector v a which is clearly overlapping. To argue another way: ... as [] does not match G.Vector [] a ... this...
You can quite easily extract just the final part from a URI. Extract the uriPath from the parsed URI, and then just take in reverse until you hit a slash. For example, getFinalPart :: URI -> String getFinalPart = reverse . takeWhile (/='/') . reverse . uriPath ...
No, you cannot pattern match the way you are trying to do here. A JSON Array can contain values of different types, and you cannot pattern match on all values in a list like they where one. There are several ways to solve your actual problem here. There is a...
You have to thread it all the way back up to where you need it. repr <- case playerInput of -- now you have to return something of the appropriate type, -- say, `Left "didn't get it"`, from these other cases. _ -> do let repr = ... >>= whatHandRepresents...
haskell,file-io,lazy-evaluation
You're right, this is a pain. Avoid using the old standard file IO module, for this reason – except to simply read an entire file that won't change, as you did; this can be done just fine with readFile. readCsvContents :: Filepath -> IO String readCsvContents fileName = do contents...
You don't want to do that. The simplest way of achieving what you want is the following: class HasId a where getId :: a -> UUID class HasId a => MyClass1 a where method1 = -- NOTE: Use "getId" instead of plain "id". when you define your data types you...
All you need is love and to split print into putStrLn . show and then add a simple map in-between which does the conversion: main :: IO () main = let fn '[' = '{' fn ']' = '}' fn c = c in (readLn :: IO [Integer]) >>= putStrLn...
The problem is that x (-x) is not of type Int (thanks to @leftaroundabout removed non-sense about non-valid syntax here). You want to generate two values for every x. So I guess the easiest way is to create lots of list pairs [1, -1], [2, -2], ... and then to...
parsing,haskell,integer,attoparsec
Your code snippet is far from being self-contained (in particular, imports and the definition of your Packet data type are missing), but you seem to be overcomplicating things. First, define a parser for one-digit integers. Then, use the latter as a building block for a parser for two-digit integers. After...
haskell,functional-programming,runtime,transactional-memory
(# s2#, TVar tvar# #) is an unboxed tuple. The name stg_newTVarzh is built from: The stg_ prefix, which is common to the whole GHC runtime, and stands for the spineless-tagless G-machine, an abstract machine to evaluate functional languages; newTVar which is the first part of newTVar#; the final zh,...
zoom has its own class for overloading, so no wonder just MonadState doesn't cut it. The Zoom class covers roughly the same ground as mtl, although it has somewhat more complicated machinery. In any case, you're not obligated to program in concrete monads. You can try enabling NoMonomorphismRestriction and inferring...
I assume that we'd like to have a solution for the general case where the changing type parameter is not necessarily in the right position for DeriveFunctor. We can distinguish two cases. In the simple case out data type is not recursive. Here, prisms are a fitting solution: {-# LANGUAGE...
ubuntu,haskell,vim,ubuntu-14.04,cabal
Your $PATH variable seems to be broken. In a comment you said it was /home/me/google-cloud-sdk/bin:/.cabal/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games This means that your shell (assumed to be bash) will look in the following directories /home/me/google-cloud-sdk/bin /.cabal/bin /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin /usr/games /usr/local/games when looking for executable. If you look at the second...
You can use the same applicative notation to parse the nested values like this: instance FromJSON DataMain where parseJSON (Object v) = DataMain <$> v .: "a" <*> v .: "b" <*> (Data1 <$> v .: "c" <*> v .: "d") parseJSON _ = mzero ...
the problem is main = ... main should have type IO () but you give an expression with type [[Integer]] (as the compiler tells you) - so as I think you want to output the result to the console I think you are looking for print this works for me:...
it's tricky but the thing is that the two 10s in (round (3/10))*10 don't have to be the same type but of course the bs in let roundBy b x = (round (x/b)) * b have to be. That`s why: λ> :t (round (3/10))*10 (round (3/10))*10 :: Integral a =>...
haskell,functional-programming,composition,functor,applicative
The Applicative class has the <*> operator (usually pronounced "ap", and is equivalent to Control.Monad.ap for most Monads), which combined with the <$> operator (itself just an infix alias for fmap) lets you write code like -- f :: a -> b -> c -- fa :: Applicative f =>...
Here is a function f' which does what you describe. f' :: [(String,String)] -> IO [Bool] f' = mapM $ uncurry f Let me know if something is unclear! And, just to be clear, here is how you run it: main = do res <- f' [("a.txt", "b.txt"), ("c.txt", "d.txt")]...
There are many approaches to this, mostly depending on what flavor of devops/hosting your prefer. One option is to put a dummy value in the config file and override it with an environment variable at runtime (see: https://github.com/yesodweb/yesod/wiki/Configuration#overriding-configuration-values-with-environment-variables). You can also having an extra settings file for production that overrides...
Here's something potentially interesting... {-# LANGUAGE DataKinds, KindSignatures, ScopedTypeVariables #-} import GHC.TypeLits import Data.Proxy data Bar (n :: Nat) = Bar String deriving Show bar :: KnownNat n => Bar n -> (String, Integer) bar [email protected](Bar s) = (s, natVal b) Ok, it's very pointless. But it's an example of...
First you need to understand the list data type. Here are the list data constructors: [] :: [a] (:) :: a -> [a] -> [a] where: [] create an empty list (:) takes an a , a list of a and returns a list of a with the new element...
Here is a simple example (@luqui mentioned) you should be able to generalize to your need: module Main where import Control.Monad (replicateM) import System.Random (randomRIO) main :: IO () main = do randomList <- randomInts 10 (1,6) print randomList let s = myFunUsingRandomList randomList print s myFunUsingRandomList :: [Int] ->...
shell,haskell,command-line-arguments,executable
The documentation for readProcess says: readProcess :: FilePath Filename of the executable (see RawCommand for details) -> [String] any arguments -> String standard input -> IO String stdout When it's asking for standard input it's not asking for a file to read the input from, but the actual contents of...
Here's one that I wrote a few weeks ago. You can specify the number of decimals you want (correctly rounded), or just pass Nothing in which case it will print the full precision, including marking the repeated decimals. module ShowRational where import Data.List(findIndex, splitAt) -- | Convert a 'Rational' to...
A do block is for a specific type of monad, you can't just change the type in the middle. You can either transform the action or you can nest it inside the do. Most times transformations will be ready for you. You can, for instance have a nested do that...
This cannot be done currently in diagrams, although it is something we would like to have in the future. You can get part of the way there using the diagrams-canvas backend, but that only displays on a local host and cannot be embedded into a web page. The only thing...
For some reason, cabal wasn't using the version I thought it was (1.5) but (1.4) probably from the haskell platform. Uprading fixed the problem.