# Questions tagged [haskell]

28818 questions

0

votes

0

answer

6

Views

### Data types a la carte — over-engineered?

I'm working through Swiertstra's 2008 paper. I'm up to Section 3 eval addExample, just before 'Automating injections'. And boy! does it need automating.
Is it just me, or is the whole thing over-engineered? Compare this in the paper
addExample :: Expr (Val :+: Add)
addExample = In (Inr (Add (In (Inl...

1

votes

1

answer

47

Views

### Haskell Esqueleto 3 table join

These are my attempts to do a SELECT from three tables. But they don't compile and I don't understand the error (I don't know why it expects a tuple (Entity Issue, b0) instead of the triplet I think the code attempts to get).
Attempt 1:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPre...

0

votes

2

answer

24

Views

### Algebraic data type (intended) name collision.. how to?

With a bit of time on my hands, I had the idea to implement my own little music theory module in Haskell.
Starting with notes (Note) makes sense and right there and then I ran into this nasty syntactic problem, I have no idea how real Haskellers handle it.
data Note = Sharp NoteS | Flat NoteF derivi...

1

votes

2

answer

72

Views

### Haskell Nested List Comprehensions

I am studying for an exam and I am looking at an example of nested list comprehensions from the book 'Learn you a Haskell', and I was hoping if anyone could explain me step by step how to analyze it and come out with its output.
let xxs = [[1,2,3],[2,3,4],[4,5]]
[ [ x | x

1

votes

1

answer

108

Views

### Given a church encoded numeral as closure result from a CEK-machine, how to get back the number?

I have implemented the CEK-machine. Given a closure result from this algorithm and the knowledge that this closure is a Church-encoded numeral, what is the best way to print out the numeral?
Using the following types:
data Term = Var String | Abs String Term | App Term Term
data Clos = Clos String T...

1

votes

2

answer

90

Views

### Traversing Data Type with Recursive Binary Tree List in Function

I created a recursive binary tree where there can be unlimited children:
data Tree a = Leaf a
| Node [Tree a]
My issue is in the syntax during the creation of a function in order to traverse the tree.
Say I want to do something easy, like give an argument 1 and then find out Bool if 1 occurs within...

1

votes

2

answer

56

Views

### How to use -v to see a list of the files searched for in Haskell Stack

I have some Haskell code below.
-- | Determine the prime factors of a given positive integer.
module P36 where
import Data.List
import Data.Numbers (primeFactors)
prime_factors_mult :: Integer -> [(Integer, Int)]
prime_factors_mult = map encode . group . primeFactors
where encode xs = (head xs, leng...

1

votes

2

answer

74

Views

### How to write “deriving instance” declaration?

I'm trying to store a crypto hash as a field in a record type, but the compiler complains:
HashTest.hs:13:1: error:
• No instance for (Data (Digest MD5))
arising from the second field of ‘MyRecord’ (type ‘Digest MD5’)
Possible fix:
use a standalone 'deriving instance' declaration,
so you c...

0

votes

0

answer

16

Views

### Save values beyond control structures

Question: is there a way to 'store' values beyond control structures
Disclaimer: the following code framework is without any true sense -> it's only for better understanding the question...
the control structure could do 'anything' -> thats the reason why I don't wan't to return values like the str...

0

votes

0

answer

14

Views

### How to count no. element in tuples in a list of tuples and return element with no. elements in list

Need to show artists without duplicates, and number of times the artist appears in the list of tuples. Show both results paired in tuples in a list.
Im getting error: (107,1)-(109,39): Non-exhaustive patterns in function countAlbums
type Title = String
type Artist = String
type Year = Int
type Sales...

1

votes

1

answer

2.1k

Views

### How to resolve issues when getting error: Not in scope

*Main> :t putStrn
:1:1:
Not in scope: `putStrn'
Perhaps you meant one of these:
`putStr' (imported from Prelude),
`putStrLn' (imported from Prelude)
Please note that I am practising haskell programming in emacs with haskell mode.
Even while using terminal, I am getting following error:
optimight...

0

votes

1

answer

25

Views

### Truncate 1-year payments from long schedule in `\case` statement (Haskell)

I am trying to build a function to look at incoming records that detail monthly payment amounts and remaining monthly pay periods in order to derive what the total annual payments will be.
This is what I have so far:
annualizeMonthlyExpense :: MonthlyPayment -> MonthsLeftToPay -> Double -> Double
an...

1

votes

0

answer

11

Views

### (New?) Modal Operators for Foldable

This post follows in a sense my previous one.
HTNW, in response to my previous post, defined the data type 'Same' and the function 'allEq'.
So I thought that by defining the data type 'AllDifferent', the function 'allDiff' and the derived ones 'someEq' and 'someDiff', I would have obtained a kind of...

7

votes

4

answer

198

Views

### Test if all elements of a Foldable are the same

I built a function that verifies that all elements of a foldable structure are equal.
Compared to a similar function on the lists, it seems to me that the more general function is disproportionately complex, but I have not been able to simplify it.
Do you have any suggestions?
import Data.Monoid
imp...

7

votes

2

answer

137

Views

### What can the Reader monad do that applicative functions cannot?

Having read http://learnyouahaskell.com/functors-applicative-functors-and-monoids#applicative-functors , I can provide an example of the use of functions as applicative functors:
Let's say res is a function of 4 arguments and fa, fb, fc, fd are all functions that take a single argument. Then, if I'm...

3

votes

1

answer

97

Views

### How does Haskell know to retain Nothing as nothing when passed to a lambda that returns Just x?

I'm just trying to understand why this doesn't error:
Prelude> Nothing >>= (\x -> Just $ x + 3)
Nothing
If I break the lambda down into individual steps:
Prelude> Nothing + 3
:8:1: error:
• Non type-variable argument in the constraint: Num (Maybe a)
(Use FlexibleContexts to permit this)
• When c...

2

votes

2

answer

11

Views

### Functionally changing key names in serialization to aeson with Text keys

I have a json object with a manually crafted ToJSON instance. I would like to replace this with a function that does not require my explicit enumeration of the key names.
I am using 'rec*' as a prefix I would like to strip, and my fields start out as Text rather than string.
Starting with minimal...

6

votes

0

answer

104

Views

### How can I optimize parallel sorting to improve temporal performance?

I have an algorithm for parallel sorting a list of a given length:
import Control.Parallel (par, pseq)
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Environment (getArgs)
import System.Random (StdGen, getStdGen, randoms)
parSort :: (Ord a) => [a] -> [a]
parSort (x:xs) = force...

1

votes

1

answer

78

Views

### How to use partials inside markdown?

I'm just starting out with Hakyll and am working with the default site that comes with hakyll init. I tried putting the following in 2015-08-12.spqr.markdown:
$partial('includes/DB.hs')$
It didn't work as expected - the post just showed the literal text $partial('includes/DB.hs')$. It didn't pull in...

1

votes

2

answer

412

Views

### Convert Type with ByteString to Text?

Using conduit, my private repo code fails to compile:
Expected type: ConduitM
Text Void (Control.Monad.Trans.Resource.Internal.ResourceT IO) ()
Actual type: ConduitM
ByteString
Void
(Control.Monad.Trans.Resource.Internal.ResourceT IO)
()
How can I define a function?
type Helper a = ConduitM a Void (...

1

votes

1

answer

1.2k

Views

### How to make a Makefile for a program for Haskell Language?

i'm new in Haskell language and i want to create a makefile for a haskell program that i'm working on it right now. But i'm not sure how to do that.
Thank you :)

0

votes

1

answer

16

Views

### How to use indexed monad as FSM?

I am trying to create a simple state machine that changes color state when input is valid:
Red -> Green -> Blue -> Red ...
I want to be able to explicitly define the state transitions. After reading What is indexed monad? and Steve Diehl's What I Wish I Knew, the indexed monad seems to be what I ne...

0

votes

0

answer

13

Views

### Algebraic Types - Haskell

I am working around with agebraic types in Haskell, doing some exercises from a worksheet. I got the following exercises:
Define an algebraic type Point for representing (the coordinates of) points in twodimensional space.
My code for this exercise:
data Point = Point Float Float
deriving (Show)
Usi...

1

votes

1

answer

60

Views

### Cartesian product not working for applicative

I was trying to understand applicative and how i can use it as a cartesian product between K functions and N parameters ,and i can't comprehend why i can't do the following:
[Just (+1),Just (+2)] [Just 1 ,Just 2] renders
Error
* Couldn't match expected type `Maybe Integer -> b'
with actual type `M...

1

votes

3

answer

78

Views

### Is there a way to generalise multiple generators and randoms in haskell

I'm learning Haskell.
Average of large number of Dice Rolls in Haskell
How shall I make the below code work with multiple dices say 8 dices) instead of repeatedly creating let rolls..3,4,5...etc...
module Dice where
import System.Random
import Data.List
dice = do
g

1

votes

4

answer

138

Views

### Zip list of different lengths

I'm just starting with Haskell and I'm not sure how to do this but when I have an input like [1,2,3,4] [5,6,7,8,9,10,11,12] the output should be [[(1,5),(2,6),(3,7),(4,8)][(1,9),(2,10),(3,11),(4,12)]]. I tried to do something, see my code below. But this only works for a list of a specific size. I'm...

1

votes

1

answer

43

Views

### Implementing sequenceAL for lists

Typeclassopedia (Haskell Wiki) has this exercise in Applicative's section:
Implement a function
sequenceAL :: Applicative f => [f a] -> f [a]
I could only do it, if used the do notation (requiring Monad f to be added to the context:
sequenceAL :: (Monad f, Applicative f) => [f a] -> f [a]
sequenceAL...

1

votes

2

answer

45

Views

### Filtering by length of lines in file giving unexpected result

I am working my way through Learn You a Haskell for great good. I am currently on the files and streams section of Chapter 9. For some reason, when I try to pipe code into one of the example Haskell programs, I do not get the same output as the book. Using ConEmu for Linux commands on Windows. For e...

1

votes

1

answer

68

Views

### How does one use an instance function in Haskell when ghc complains it is not in scope, despite imports?

In A Gentle Introduction to Haskell, Version 98, it is said:
Instance declarations are not explicitly named in import or export
lists. Every module exports all of its instance declarations and every
import brings all instance declarations into scope.
This seems like good sense to me. Anyhow, when I...

1

votes

1

answer

47

Views

### What is wrong with my data constructor import/use, when ghc suggestion is to add constructor to import list?

I have the following line of code where I'm trying to extract the internal raw type so I can work with it directly:
SDL.Internal.Types.Window (rawWindow) = window
My import looks like:
import qualified SDL.Internal.Types (Window)
The error I get is below; it seems I'm already doing what it sugg...

1

votes

1

answer

75

Views

### Implementing Cont Applicative instance

I got the following error when implementing the Applicative instance for Cont.
Couldn't match expected type ‘r’ with actual type ‘Cont r b’ ‘r’ is
a rigid type variable bound by ...
newtype Cont r a = Cont {(>>-) :: (a -> r) -> r}
instance Functor (Cont r) where
-- fmap :: (a -> b) ->...

1

votes

1

answer

89

Views

### Haskell: IOArray is too slow when reading and writing a lot

I wrote a small code in Haskell. Could you give a solution to improve performance?
Input: Height and Width of a grid. Locations of point shown as '#'
4 4
##..
#...
...#
....
Output: grid of numbers showing 'Manhattan distance' to each nearest point.
0 0 1 2
0 1 2 1
1 2 1 0
2 3 2 1
To set a lot of nu...

1

votes

2

answer

86

Views

### Haskell IO indentation

I tried to rewrite that program, which is working:
nameIOite :: IO ()
nameIOite = do
putStrLn 'What's your name ?'
name

1

votes

2

answer

117

Views

### A faster way of generating combinations with a given length, preserving the order

TL;DR: I want the exact behavior as filter ((== 4) . length) . subsequences. Just using subsequences also creates variable length of lists, which takes a lot of time to process. Since in the end only lists of length 4 are needed, I was thinking there must be a faster way.
I have a list of functions....

1

votes

2

answer

118

Views

### Haskell - separate a list of pairs in two lists using fold

So, I am given a list containing tuples and I need to break it down into two lists, the first list containing the elements with odd index and the second list containing the elements with even index, must be done using fold, here is my attempt:
breakList :: [(Integer, Integer)] -> [[(Integer, Integer...

1

votes

2

answer

75

Views

### Get all the TypeRep's in a value using generic programming

Is there a way to get a list of all the TypeRep's inside a value using generic programming?
For instance, could one define a function:
typeReps :: (Data a, Typeable a) => a -> [TypeRep]
in such a way that:
>>> typeReps (1 :: Int, 'a')
[(Int, Char), Int, Char]
>>> typeReps (Foo ['a', 'b'])
[Foo, [Cha...

1

votes

2

answer

73

Views

### Why is the type signature of getEvent what it is?

The type signature for getEvent from the UI.NCurses library has the type signature
Window -> Maybe Integer -> Curses (Maybe Event)
However having used this function a bunch I am still not quite sure what the Window is used for. The documentation says that it
Get[s] the next Event from a given windo...

1

votes

2

answer

92

Views

### How do I show relationships between type variables

For the types Door and Hallway:
data DoorState :: Type where
Opened :: DoorState
Closed :: DoorState
Locked :: DoorState
deriving (Bounded, Enum, Eq, Ord, Show)
data Door :: DoorState -> Type where
Door :: {material :: String} -> Door s
deriving (Show)
data Hallway :: [DoorState] -> Type where
Origi...

1

votes

2

answer

90

Views

### how to correctly apply the foldr function

Im attempting to find the max element of a list, where the elements are a data type created by myself, using a fold instead of doing it recursively. However i end up with an error 'couldn't match type'. As im fairly new to haskell im having trouble seeing the problem and wish to know how to correct...

1

votes

2

answer

61

Views

### Accumulating [State s a] results

What I did
I found myself writing some kind of 'renderer', where at some point I had a list of state-transitions:
[State String [a]]
I wanted to apply them one after the other. I could do this with sequence, which brought me to
State String [[a]]
Then I had to flatten the result from list-of-lists t...