Menu
  • HOME
  • TAGS

Haskell powerset function - How to avoid Couldn't match expected type `IO t0' with actual type `[[Integer]]'

haskell

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:...

Generating instances for n-depth structures?

haskell

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...

Where to store API keys and other 'secrets' in a yesod app

haskell,yesod,api-key

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...

IO Monad Example

haskell

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...

Normal probability density function - GSL equivalent in Haskell

haskell,statistics,gsl

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 - Could not deduce … from Context error - OpenGL AsUniform class type

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...

Haskell list comprehension compilation error

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)?...

Why is f <$> g <$> x equivalent to (f . g) <$> x although <$> is not right-associative?

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...

Haskell: `==' is not a (visible) method of class

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...

Refactor an IO recursive loop into a monad folding in Haskell

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 ...

Setting id and class with the haskell diagrams package

haskell,svg,haskell-diagrams

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...

How to extract the final part of the URL's path in Haskell

haskell

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 ...

Mapping with IO actions in Haskell

list,haskell,io

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")]...

When will travis-ci support ghc 7.10?

haskell,travis-ci

Using multi-ghc-travis, you can also set up Travis-CI for ghc 7.10 (apart from other versions).

How do I avoid writing this type of Haskell boilerplate code

haskell,boilerplate

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...

Haskell stripping function of syntactic sugar

haskell,syntactic-sugar

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...

Why does GHCI get “stuck” in an error state after an error?

haskell,monads,io-monad

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...

How to work with Cabal API

haskell,cabal

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...

Tokenizer identifier in Haskell

haskell

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...

Stopping condition on a recursive function - Haskell

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...

How do I use zoom with a MonadState constraint of a newtype?

haskell,monad-transformers

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...

Applicative style understanding

haskell,applicative

<**> from Control.Applicative is flip <*>. Your example can work with that, slightly rearranged: >((+) <$> Just 3 <*> Just 5) <**> ((+) <$> Just 6) Just 14 ...

Can't find defaultTimeLocale in Data.Time.Format

haskell,cabal

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.

Unable to create a custom header to use it in “withManager”

haskell

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...

Custom deriving(Read,Show) for enum type

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...

What are the most common bugs in OCaml/Haskell/Scala programs? [closed]

scala,haskell,types,ocaml

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...

Hook into GHC runtime system

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,...

Why is lazy evaluation in Haskell “not being lazy”?

haskell,lazy-evaluation

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..] ...

Why doesn't `iterate` from the Prelude tie the knot?

haskell,tying-the-knot

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...

Cabal sandbox is using a global dependency. Could not resolve

haskell,cabal

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 Lempel Ziv 78 Compression

haskell

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...

Running executable files using Haskell

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...

First three items of a list in Haskell

haskell

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...

Is there any function in Haskell that applies a two argument function to two lists, element by element?

haskell

> :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...

How to “wrap” monadic return value

haskell,monads

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...

Haskell IO - read from standard input directly to list

haskell

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...

attoparsec: succeeding on part of the input instead of failing

haskell,attoparsec

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...

Combining Event and an attribute in threepenny-gui

haskell,threepenny-gui

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...

logical expression evaluator Haskell

haskell

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) =...

Get each fibbonacci value in haskell

haskell,fibonacci

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...

What is haskellng? What is the difference between 'haskellPackages' and 'haskellngPackages'?

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...

perform a function on first elements of list

haskell

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 make recipe fails for Paradox theorem prover using GHC

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....

Haskell - generate and use the same random list

haskell,random

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] ->...

apply a transformation with function inline

haskell

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...

Where are line breaks allowed within Haskell expressions?

haskell,coding-style

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...

Specifying a constaint for a class

haskell,typeclass

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...

How to convert a Rational into a “pretty” String?

haskell,formatting,rational

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...

Constructor that lifts (via DataKinds) to * -> A

haskell,data-kinds

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. ...

How does Frege generalize number literals?

haskell,frege

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...

Type ambiguity of arithmetic expression when wrapped in a function

haskell

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 =>...

From and ToJSON in Haskell - a nested data

haskell

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 ...

Haskell do clause with multiple monad types

haskell,monads

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...

Haskell: When declaring a class, how can I use a type variable that is not immediately in the constructors?

haskell

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...

How can I express the type of 'takeWhile for vectors'?

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 ->...

Can I generalize GADTs that use type tags?

haskell,type-families

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 -> *)...

importing haskell module says “not in scope”

class,haskell,instance

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....

GHC complains about overlapping instances when in fact they are not

haskell,ghc,instances

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...

Haskell return lazy string from file IO

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...

Generating Infinite List in Haskell

haskell,list-comprehension

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...

Haskell lens: let binding of Traversal'

haskell,traversal,lens

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...

Thread blocked indefinitely in an MVar operation

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) =>...

Pipeline-like operation using TChan

multithreading,haskell,stm

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...

Haskell: Type mismatch in function using foldr

haskell

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...

Why are takeR, dropR and splitAtR missing from Data.Sequence?

haskell,containers,sequence

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...

Fold over a heterogeneous, compile time, list

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) =>...

Best practice for handling data types from 3rd party libraries in Haskell?

haskell,types

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...

Recursion scheme in Haskell for repeatedly breaking datatypes into “head” and “tail” and yielding a structure of results

haskell,recursion

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...

Decremented value called in the recursion in Haskell

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...

compile-time vs. run-time cost of Hamlet templates

haskell,yesod,hamlet

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...

Changes in other elements based on listbox selections in threepenny-gui

haskell,threepenny-gui

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...

haskell beginner - my simple sort

haskell

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...

How to improve the performance of Haskell IO?

haskell,io

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...

Uniqueness and other restrictions for Arbitrary in QuickCheck

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,...

Idiomatic list construction

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...

Implementing map on a tree using fold

scala,haskell

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...

Rank N types in let bindings

haskell,gadt

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,...

Infix operator with missing argument

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...

Instance of Show for Lambda

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) ...

Can I have an unknown KnownNat?

haskell,dependent-type

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...

Define function in Haskell with computations in arguments

haskell

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...

How do I reuse an intermediate value in chain of Haskell Either binds?

haskell,binding,bind,chain

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...

issues with installing newer cabal version for haskell vim now

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/sb‌​in:/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/sb‌​in /usr/bin /sbin /bin /usr/games /usr/local/games when looking for executable. If you look at the second...

How can I express foldr in terms of foldMap for type-aligned sequences?

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 ::...

automatic typing of nested lists

haskell

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,...

Replace all [ ] with {} - as short as possible [on hold]

haskell

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...

Keep track of loop without a counter

haskell

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 _ [] = []...

How to use Proxy properly?

haskell

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) ...

Pattern Match Vector Value in Data.Aeson

haskell,aeson

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...

Easier way to apply multiple arguments in Haskell

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 =>...