FAQ Database Discussion Community

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

So, when I compile the following piece of code edited: instance (Eq a) => PartOrd a where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _==_ = False xs /= ys = not (xs == ys) I get: `==' is not a (visible) method of class...

## Get each fibbonacci value in haskell

I'm learning haskell and I have the following code: fib a b = a : fib b (a + b) findFibSum = sum [x | x <- fib 1 2, mod x 2 == 0 && x < 100] If I run findFibSum nothing happens, it just sits there. Shouldn't...

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

In Haskell, I recently found the following function useful: listCase :: (a -> [a] -> b) -> [a] -> [b] listCase f [] = [] listCase f (x:xs) = f x xs : listCase f xs I used it to generate sliding windows of size 3 from a list, like...

## How to improve the performance of Haskell IO?

It seems that Haskell's IO is relatively slow. For example, comparing Haskell with Python #io.py import sys s=sys.stdin.read() sys.stdout.write(s) , -- io.hs main = do s <- getContents putStr s Their performance (gen.py writes 512k data into stdout): The Python version: \$ time python gen.py | python io.py > /dev/null...

## First three items of a list in Haskell

I am very new to Haskell, and struggling a bit with a function here. The premise is simple enough: Run through a list, and combine each 3 items next to each other with another function and return a list with the results. The problem is to do it in a...

I have been reading this StackOverflow post in which we are advised to use the haskellng package set. I have also read this but I did not understand what haskellng is. I have read this too, but I still don't know what haskellng is. Could someone please explain what haskellng...

## Can I have an unknown KnownNat?

I wonder if I can have my cake and eat it too regarding KnownNats. Can I write code that uses Nats that may be both KnownNats and UnknownNats (SomeNats?). For example if I have a dependently typed vector Vec (n :: Nat) a, can I write code that works both...

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

I want to define a function, <-? to check whether an element is in a list/set/map. module Test where import qualified Data.Map as Map import qualified Data.Set as Set class Memberable a where (<-?) :: b -> a -> Bool instance Memberable [x] where (<-?) = elem instance Memberable (Map.Map...

## Applicative style understanding

I would like to write something as the following: (+) <\$> Just 3 <*> Just 5 <*>' (+) <*> Just 6 However the problem is that I need to somehow flip <*>. What is the idiomatic way in Haskell to do the type of chaining I'm trying?...

## Specifying a constaint for a class

I have three data declarations in the different modules: data Data1 = Data1 { id :: UUID , field2 :: String , field3 :: Int } data Data2 = Data2 { id :: UUID , field1112 :: String , field4433 :: String } data Data3 = Data3 { id ::...

## Uniqueness and other restrictions for Arbitrary in QuickCheck

I'm trying to write a modified Arbitrary instance for my data type, where (in my case) a subcomponent has a type [String]. I would ideally like to bring uniqueness in the instance itself, that way I don't need ==> headers / prerequisites for every test I write. Here's my data...

## Force GHC using local files

I'm making some "experiments" on a haskell module and I have a problem with a source file I wish to modify. I have many reasons to think that GHC seek the installed (with cabal) library on my system and not the local sources files. I deleted the *.o files locally...

I would like to install this vim plugin: https://github.com/begriffs/haskell-vim-now When trying to run the suggested installation script: curl -o - https://raw.githubusercontent.com/begriffs/haskell-vim-now/master/install.sh | bash I get: --- Cabal version 1.18 or later is required. Aborting. I then try to install a newer version of cabal: [email protected]:~/Downloads/cabal-install-1.22.6.0\$ ./bootstrap.sh The response I get:...

## importing haskell module says “not in scope”

I created a Tree structure in a file called Tree2.hs module Tree2 ( Tree ) where data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) then I imported it and tried to use it as an instance of a class import qualified Tree2 class YesNo...

## Setting id and class with the haskell diagrams package

I am working with the diagrams package for haskell, and I am using the SVG backend. I embed the SVG markup directly into an HTML document, so that the graph as a part of a web page. I have built a pretty cool looking bar graph, and I would like...

## Normal probability density function - GSL equivalent in Haskell

I am trying to find the best way to draw from a normal distribution. I want to be able to use the normal probability density function (and its cumulative) in Haskell. To put it simply, I want to use the functions on this page without using the GSL binding... I...

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

I have a powerset implementation that I'm trying to run here: http://rextester.com/runcode. I'm still getting this error and can't figure out how to make it right. I'm trying to read as much as possible about IO in haskell but it is super hard for me. import Control.Monad (filterM) powerset =...

## Implementing map on a tree using fold

I am trying to implement a map using fold. I could do so in Haskell data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b foldTree EmptyTree d _ =...

## Pattern matching on variant without deconstructing in Haskell

In the following code, the function disp is defined by de-constructing Sum b c and then immediately reconstructing it. The problem is that I don't need b and c, only the fact that it is of type Sum. data Expr = Name String | Sum Expr Expr deriving(Show) disp (Sum...

## Generating Infinite List in Haskell

So, been going over some old exams in preparation for my upcoming one and came across this question: Write Haskell code to define ints :: [Int] an infinite list of the following form: [0, 1, -1, 2, -2, 3, -3, 4, -4..] I've been plugging at it for the past...

## How does Frege generalize number literals?

It appears that Frege can evaluate 1/2 to return the Double value 0.5. The literal 1 is of type Int. It seems to be promoted to Double, which is a type in the Real class and thus knows the / operator. How does this happen? Is it using the Haskell...

## Infix operator with missing argument

Is it possible with Haskell to have an operator (infix function) working with a missing argument ? (rather like - meaning a subtraction or a negative sign) For example, I have this operator : data1 <*> data2 Is it possible to make it work with a default value if first...

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

I have two functions, one with a MonadState constraint of the wrapped type, the other has a MonadState constraint of the unwrapped type. I'd like to seamlessly run the second function within the first. For example: import qualified Control.Monad.State.Strict as MTL import Data.Monoid (Sum) import Control.Lens.Zoom (zoom) import Control.Lens.Wrapped (_Wrapped')...

## apply a transformation with function inline

Starting from a simple case of "fold" (I used (+) but can be anything else): Prelude.foldl (+) 0 [10,20,30] is it possible apply an inline transformation similar to (that doesn't work): Prelude.foldl ((+) . (\x -> read x :: Int)) 0 ["10","20","30"] In case not, is there an alternative to...

## Haskell - Could not deduce … from Context error - OpenGL AsUniform class type

I'm working on making my data types general instead of taking in the OpenGL type GLfloat. So I started making it take in type a and then just replacing everything with that. Now, I've come to a point where I'm setting uniform variables, but they take in GLfloat's. I'm using...

## Can't find defaultTimeLocale in Data.Time.Format

According to the doc on Hackage, Data.Time.Format exposed defaultTimeLocal. However, when I try to use it, it doesn't exits. When I look at the code, it doesn't seems to be exposed either (if I generate the doc from the source, I don't see this defaultTimeLocale). Is it because it needs...

## Pipeline-like operation using TChan

I want to implement a pipeline between two threads. I have thread A that take the data, process it, and send it to thread B. I have a MVar that check if the data is completely processed However, I'm having an exception *** Exception: thread blocked indefinitely in an STM...

## How do I avoid writing this type of Haskell boilerplate code

I run into this situation often enough for it to be annoying. Let's say I have a sum type which can hold an instance of x or a bunch of other things unrelated to x - data Foo x = X x | Y Int | Z String | ...(other...

## How to use Proxy properly?

Why this code doesn't work? class Foo a where foo :: Proxy a -> Int bar :: Foo a => a -> Int bar _ = foo (Proxy :: Proxy a) It fails to compile with the message: Could not deduce (Foo a0) arising from a use of `foo' from...

## perform a function on first elements of list

In an attempt to write the Havel-Hakimi algorithm in Haskell, I wrote following function to subtract 1 from the first n elements of a list. decrease_first :: Int -> [Int] -> [Int] decrease_first 0 l = l decrease_first n (x:xs) = (x-1):decrease_first (n-1) xs This code works, but as I...

## Haskell lens: let binding of Traversal'

I'm a bit confused and don't know where to look for the information/explanation of the following "issue" (it's not an issue per se, but more of a situation where I don't understand what is wrong behind the scenes): I have a monad transformer stack with StateT. At some point in...

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

First of all, my apologies for the non-descriptive title. Since I have no idea what's actually going on I can't really make it any more specific. Now for my question. I have implemented the following snippet for problem 23 of the 99 Haskell problems, which should randomly select n items...

## Cabal sandbox is using a global dependency. Could not resolve

I'm trying to add timerep onto an existing application. I can't get it to resolve my dependencies. It looks like it is using the globally installed version of time == 1.4.2, when >= 1.5 would be ideal for my application. How can I get cabal to use time 1.5? I've...

## Haskell list comprehension compilation error

I want to create a function that given two lists (of floats, but could be anything) gives a list with all the combinations of taking two elements from the first list and putting it in the last and all the combinations of the former putting one of the elements from...

## Haskell - generate and use the same random list

In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it. How can I overcome this problem?...

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

Now when we have these fancy type-systems to prevent null-pointer bugs and memory bugs and all, what common bugs are left? Can these bugs be prevented with different type-systems or further programming language research? Edit: Do we know what bugs are common in functional programming? Edit 2: -3 question with...

## Where are line breaks allowed within Haskell expressions?

Background Most style guides recommend keeping line lengths to 79 characters or less. In Haskell, indentation rules mean that expressions frequently need to be broken up with new lines. Questions: Within expressions, where is it legal to place a new line? Is this documented somewhere? Extended question: I see GHC...

## Instance of Show for Lambda

So, I have already defined the lambda data type as such: data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq, Show) Now I want to implement an instance of Show myself. I have already the function...

## Define function in Haskell with computations in arguments

How can I define a function in Haskell like this: x(0) = 1 x(2*k) = sin(k) * cos(k) x(2*k+1) = cos(k/2) - tan(2*k) Haskell does not allow to define a function with computation in its arguments. It will raise a "Parse error in pattern" error. If I try to define...

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

Given an ADT like data K = A | B Bool the DataKinds extension allows us to lift it into kinds and types/type constructors K :: BOX 'A :: K 'B :: 'Bool -> K Is there a way to add a constructor to K that lifts to the type...

## automatic typing of nested lists

While working through Richard Bird's Thinking Functionally With Haskell, I came across a demonstration of Haskell's type system that I find puzzling (p. 44): [ [], [[]], [[[]]] ] :: [[[[a]]]] To explain, let the main list have type [b]. The first element is a list, so b=[c]. The second...

## How to work with Cabal API

I would like to "interact" with Cabal during the test phase (like exitcode-stdio-1.0) using the relative API (https://www.haskell.org/cabal/release/cabal-latest/doc/API/Cabal/Distribution-Simple-Test-ExeV10.html) to customise for example the final output. How can I do that? I cannot find the right documentation.

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

I'm sure this has been answered but apparently I don't know what to search for. I am working on my first non-trivial Haskell program -- a simulation of a card game I enjoy. I have the program working but there is a situation that I am certain can be handled...

## Why is `++` for Haskell List implemented recursively and costs O(n) time?

As I understood, a List in Haskell is a similar to a Linked-List in C language. So for expressions below: a = [1,2,3] b = [4,5,6] a ++ b Haskell implement this in a recursive way like this: (++) (x:xs) ys = x:xs ++ ys The time complexity for that...

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

Given the code below: import Data.List; main = (readLn :: IO [Integer]) >>= print . subsequences It takes a list of integers from standard input (for example [1,2,3]) and outputs something like: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] I want it to be like this: {},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}} so my goal is to replace every [ and...

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

I'm playing around with type-aligned sequences, and in particular I'm messing around with the idea of folding them. A foldable type-aligned sequence looks something like this: class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b...

I am trying to install the paradox theorem prover sourced from here. When I run the makefile this is the command that runs: ghc -optl -static -lstdc++ -I../instantiate -I../minisat/current-base ../minisat/current-base/Solver.or ../minisat/current-base/Prop.or ../instantiate/MiniSatWrapper.or ../instantiate/MiniSatInstantiateClause.or -fglasgow-exts -O2 -static -threaded -main-is Paradox.Main.main --make Paradox.Main -o paradox And it results in several errors like...

## haskell beginner - my simple sort

I have this code for sorting list of even number of items: sort [] = [] sort l = sortN l (length l) sortN l 0 = l sortN l n = sortN (swap l) (n - 1) swap [] = [] swap (a:b:t) | a <= b = a...

## GHC complains about overlapping instances when in fact they are not

I have the function toAVector defined like this: class Elt a => ToAVector v a where toAVector :: v a -> A.Array DIM1 a instance Elt a => ToAVector [] a where toAVector l = A.fromList (Z :. P.length l) l instance (Elt a, G.Vector v a) => ToAVector v...

## Running executable files using Haskell

Say there's a C++ code that I've compiled into an executable using: g++ test.cpp -o testcpp I can run this using Terminal (I'm using OS X), and provide an input file for processing inside the C++ program, like: ./testcpp < input.txt I was wondering if doing this is possible, from...

## attoparsec: succeeding on part of the input instead of failing

I have an attoparsec parser, and tests for it, what annoys me is that if I comment part of the parser and run the tests, the parser doesn't return Left "parse error at line ..." but instead I get Right []. Note that I'm using parseOnly to make it clear...

## Haskell: Type mismatch in function using foldr

I don't understand why there is an error in these functions: countEqualPairs:: Eq a => [a] -> Int countEqualPairs (s:ss) = foldr test s ss test :: Eq a => a -> a -> Int test s c = if (c == s) then 1 else 0 Error Message: Could...

## Custom deriving(Read,Show) for enum type

Let's say I have this enumeration type: data TVShow = BobsBurgers | MrRobot | BatmanTAS and I want to define instances for Read and Show with the following behavior: show BobsBurgers = "Bob's Burgers" show MrRobot = "Mr. Robot" show BatmanTAS = "Batman: The Animated Series" read "Bob's Burgers" =...

## Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

## From and ToJSON in Haskell - a nested data

I have this: data Data1 = Data1 { field1 :: Int, field2 :: Int } data DataMain = DataMain { a :: String , b :: Bool , subData :: Data1 } And JSON { a: 'some value', b: 'some value2', c: 'some value3', d: 'some value4', } And here...

## How to bring a data kind to the value level?

I have something like this in my code: data SomeKind = Kind1 | Kind2 deriving Eq data SomeValue (t :: SomeKind) = SomeValue someValue1 :: SomeValue Kind1 someValue1 = SomeValue someValue2 :: SomeValue Kind2 someValue2 = SomeValue I want to get the kind that's in the type level to the...

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

Haskell beginner here. I've defined the following types: data Nat = Z | S Nat data Vector a n where Nil :: Vector a Z (:-) :: a -> Vector a n -> Vector a (S n) infixl 5 :- I'm trying to write the function, takeWhileVector which behaves the...

I wrote the following logical expression evaluator. It works for simple 2-member expressions, and it runs but produces a fault for expression containing other expressions as the second/first member. Here's my code. data Expression = Literal Bool | Operation Operator Expression Expression data Operator = AND | OR eval ::...

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

I want to display some Rational values in their decimal expansion. That is, instead of displaying 3 % 4, I would rather display 0.75. I'd like this function to be of type Int -> Rational -> String. The first Int is to specify the maximum number of decimal places, since...

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

So I have a simple example layout with a listbox, a button and a textarea, where clicking the button changes the text in the textarea: import Control.Applicative import Control.Monad import Data.Maybe import qualified Graphics.UI.Threepenny as UI import Graphics.UI.Threepenny.Core main :: IO () main = startGUI defaultConfig setup setup :: Window...

## Fold over a heterogeneous, compile time, list

I have a list of heterogeneous types (or at least that's what I have in mind): data Nul data Bits b otherBits where BitsLst :: b -> otherBits -> Bits b otherBits NoMoreBits :: Bits b Nul Now, given an input type b, I want to go through all the...

## Hook into GHC runtime system

I have been looking at how transactional memory is implemented in Haskell, and I am not sure I understand how the STM operations exposed to the programmer hook into the runtime system functions written in C. In ghc/libraries/base/GHC/Conc/Sync.hs of the git repo, I see the following definitions: -- |A monad...

## What is the type of the variable in do-notation here in Haskell?

The codes below looks quite clear: do x <- Just 3 y <- Just "!" Just (show x ++ y) Here the type of x is Num and y is String. (<- here is used to take actual value out of the Monad) However, this snippet looks not so clear...

## Thread blocked indefinitely in an MVar operation

I have been attempting to debug a problem when using multiple MVars, however to no luck. My code uses two MVars: one to store the servers current state, and another to pass network events to and from the client threads. However after connecting and disconnecting several times, the server stops...

## Idiomatic list construction

I'm very new to Haskell and functional programming in general, so I don't really know how to make this code idiomatic: type Coord = Double data Point = Point Coord Coord Coord deriving Show type Polyline = [Point] -- Add a point to a polyline addPoint :: Polyline -> Point...

## Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

## Generating instances for n-depth structures?

By n-depth structure I mean some structure that nests one kind of structure n times, for example [[a]] is a 2-depth list. I was randomly thinking about an instance of Functor, Foldable and Traversable for a 3-depth list ([[[a]]]) today, and found some regularity as you can see below: instance...

## Couldn't match expected type `((Int, Int, Int) -> Int, b5)'

do not know why debug many times still have error even if explicit declare type int, do not know where do b0, a0, b2 come from ghc -o hello main.hs [1 of 1] Compiling Main ( main.hs, main.o ) main.hs:92:10: Couldn't match expected type `(Int, b0)' with actual type `(Int,...

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

When I tried the following code in cghi: take 1 \$ take 1 \$ repeat [1..] I was expecting the result of 1 instead of [[1,2,3,4,5,6,7,8,9,10,... printing on my terminal. Why is lazy evaluation not functioning as I'm hoping under such situation?...

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

Data.Sequence has takeWhileR and dropWhileR for efficient deconstruction of Seqs from the right. However, takeR, dropR and splitAtR are conspicuously absent. take and drop are implemented in terms of splitAt. So, do finger trees not admit an efficient splitAtR or was this functionality not included for some other reason? (Separate...

I'm using a graphic library in Haskell called ThreePennyUI. In this library the main function returns a UI monad object. This causes me much headache as when I attempt to unpack IO values into local variables I receive errors complaining of different monad types. Here's an example of my problem:...

## When will travis-ci support ghc 7.10?

I'd like to use travis-ci on my Haskell projects, but they require the latest version of GHC.

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

Why is f <\$> g <\$> x equivalent to (f . g) <\$> x although <\$> is not right-associative? (This kind of equivalence is valid in a popular idiom with plain \$, but currently \$ is right-associative!) <*> has the same associativity and precedence as <\$>, but behaves differently! Example:...

## Haskell return lazy string from file IO

Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

## Rank N types in let bindings

So I've done this... {-# LANGUAGE Rank2Types, GADTs #-} type Record fields = forall t. fields t -> t data PersonField t where Name :: PersonField String Age :: PersonField Int type Person = Record PersonField And then this... nigel :: Person nigel Name = "Nigel" nigel Age = 39...

## Pattern Match Vector Value in Data.Aeson

I am using Data.Aeson to parse JSON to my custom type. I try to pattern match Vector Value (Array) in my FromJSON instance, but don't know how I can do it. JSON value key can have a value of a String, a list of String or a list of list...

## how to handle capital case in JSON?

This is a stupid question, and I have tried to understand from different tutorials. When having a JSON with capital case Haskell crashes as explained by others (https://mail.haskell.org/pipermail/beginners/2013-October/012865.html). As suggested it could be solved with deriving from deriveFromJSON. DeriveJSON requires a function input, how should I write the derive statement...

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

I'm trying out a yesod applications which I will eventually put up on github or similar. I will use oauth2 with google which means I have to provide an email and secret token. Which I obviously do not want up on github. What is a good place to store these...

## importing inline-c modules in ghci

I would like to import some inline-c generated functions in a ghci session. All source and object files are in a src/ subfolder but I get import error: src/Main.hs:3:8: Could not find module ‘Test1’ I include all files for reference. Thanks in advance Main.hs module Main where import Test1 main...

## Mapping with IO actions in Haskell

I have a function that takes two filenames, and reads the contents of those two files into Strings, and then returns if they match or not. Here's the function: f :: String -> String -> IO Bool f fileName1 fileName2 = do str1 <- readFile fileName1 str2 <- readFile fileName2...

## How to “wrap” monadic return value

I have the following code: data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq) newtype APNSItem = Item Put createNotificationIdentifierItem :: APNSIdentifier -> APNSItem <--- here createNotificationIdentifierItem (Identifier identifier) = do putWord8 3 putWord16be 4 putWord32be identifier How can I "wrap" the Put monad with an APNSItem? Do I...

Haskell IO system is super hard to understand for me so i have question : How to read from standard input to list ? I know that there is function getLine :: IO String and interact. But i do not know how to convert the input to list so I...

## Easier way to apply multiple arguments in Haskell

Given value f with type :: Applicative f => f (a -> b -> c), What's the best way to map arguments to the inner function. So far I've found the following: (\x -> x a b) <\$> f (flip (\$ a) b) <\$> f (\$ b) <\$> (\$ a)...

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

I'm just getting into my first real Haskell project of size (a web app), and I'm starting to run into issues with types from 3rd party libraries leaking all over my code. Here is a quick example: My Parser module imports Test.Parsec, and the exports a function (parseConfig) that returns...

## Combining Event and an attribute in threepenny-gui

I have an Event String which I want to sink into a textarea. This works fine, but now I want to combine the current value of a checkbox selection to this string. First I did this by using checkedChange of the checkbox which works, but has a problem. If the...

## How can I parse fixed-length, non-delimited integers with attoparsec?

I'm trying to parse two integers from 3 characters using attoparsec. A sample input might look something like this: 341 ... which I would like to parse into: Constructor 34 1 I have two solutions that work but which are somewhat clunky: stdK :: P.Parser Packet stdK = do P.char...

## Keep track of loop without a counter

Say, I got a list which length can be odd or even. Every iteration , I remove two items from the list. If there is one or no item at the end, I end the execution. If I store (length list)/2 every loop, I will get e.g. [5,4,3...] for a...

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

I am using Network.URI to parse a url (String). How can I get from the returned URI (parseUri url) the last part of the path? Or there are better alternatives than Network.URI? For example from: http://www.foo.com/foo1/foo2/bar.html?q=2&q2=x#tag I would like to get just "bar.html"...

I'm writing this small program basically to identify each input tokens as operator/parenthesis/int. However, I encountered a problem stating that Not in scope: data constructor `Integer' Here's what I have so far (Data.Char only defines isDigit, nothing else) import Data.Char (isDigit) data Token = TPlus | TTimes | TParenLeft |...

## Type ambiguity of arithmetic expression when wrapped in a function

I am writing a simple function on the GHCi command line (7.8.3) let roundBy b x = (round (x/b)) * b When evaluated, it gives an error about ambiguity (error message at bottom). However, if I substitute the values, the same expression can be evaluated fine. Prelude> (round (3/10))*10 0...

Consider the following IO code: ghci> let x = return 100 :: IO Int ghci> :t do { a <- x; print a; return 500 } do { a <- x; print a; return 500 } :: Num b => IO b My understanding of do notation/bind is that the...

## Haskell stripping function of syntactic sugar

I'm wondering how would the following function look without any syntactic sugar: tails1 :: [a] -> [[a]] tails1 [] = [[]] tails1 [email protected](x:xs') = xs:tails1 xs' I'm mostly concerned with the usage of the @ operator, I've tried what follows, but that's obviously not the correct way tails1 ((:) x...

## Can I generalize GADTs that use type tags?

I wrote an alpha-beta search in Haskell that uses the NextMoveTag type family to ensure that the game state and moves generated from that game state are valid for the player whose turn it is: {-# LANGUAGE GADTs, EmptyDataDecls, DataKinds, TypeFamilies #-} data MoveTag = ComputerMoveTag | PlayerMoveTag type family...

## Refactor an IO recursive loop into a monad folding in Haskell

I writing a tcp server, and here's my main loop method: serverLoop :: Socket -> IO () serverLoop sock = do (conn, _) <- accept sock forkIO \$ handleConn conn serverLoop sock (Note: handleConn :: Socket -> IO () is a function specific to my program.) I would like to...

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

I just wanted to multiply two lists element by element, so I'd pass (*) as the first argument to that function: apply :: Num a => (a -> a -> a) -> [a] -> [a] -> [a] apply f xs ys = [f (xs !! i) (ys !! i) |...

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

Why isn't iterate defined like iterate :: (a -> a) -> a -> [a] iterate f x = xs where xs = x : map f xs in the Prelude?...