Avoiding namespace pollution in Haskell

I'm using lots of different records in a program, with some of them using the same field names, e.g. data Customer = Customer { ..., foo :: Int, ... } data Product = Product { ..., foo :: Int, ... } Now as the accessor function "foo" is defined twice, I get the "Multiple declarations" error. One way to avoid this would be using different modules that are imported fully qualified, or simply renaming the fields (which I don't want to do). What is the officially suggested way of dealing with th

Haskell Writing "wc -l" using Iteratee library - how to filter for newline?

I am trying to come up with equivalent of "wc -l" using Haskell Iteratee library. Below is the code for "wc" (which just counts the words - similar to the code in iteratee example on hackage), and runs very fast: {-# LANGUAGE BangPatterns #-} import Data.Iteratee as I import Data.ListLike as LL import Data.Iteratee.IO import Data.ByteString length1 :: (Monad m, Num a, LL.ListLike s el) => Iteratee s m a length1 = liftI (step 0) where step !i (Chunk xs) = liftI (step $ i + fromInt

Haskell Is this Monad/Applicative Simplfication possible?

Is it possible?, (there is a >>magic function) to simplify this: insertTransaction :: Day -> Int -> Int -> MyReaderT Bool insertTransaction day amount price = .... logTransaction :: Int -> Int -> MyReaderT Bool logTransaction amount price = do day <- currentDay insertTransaction day amount price To this: logTransaction :: Int -> Int -> MyReaderT Bool logTransaction = currentDay `>>magic` insertTransaction I think there should be one operator like &

Haskell Convention for specifying extensions in cabalized project

For any .hs file, you can specify the language extensions you rely on like so: {-# LANGUAGE Foo, Bar, Baz #-} A cabalized project can also specify language extensions on a per-project basis in the .cabal file: extensions: Foo, Bar, Baz Which of these is considered "best practice"? Should all extensions used be listed in the .cabal file, as a form of documenting which compilers your package is compatible with? Or should all extensions be noted on a per-file basis, for the sake of making cle

Why does TemplateHaskell cause GHC to load packages?

I have a trivial Template Haskell program that prints the name of the current module (Main, here): {-# LANGUAGE TemplateHaskell #-} module Main ( main ) where import Language.Haskell.TH import Language.Haskell.TH.Syntax modName ∷ String modName = $(fmap loc_module qLocation »= λmod → return (LitE (StringL mod) )) main ∷ IO () main = putStrLn modName When I compile this, I get the following Loading messages from ghc: tsuraan@localhost ~/test/modname $ ghc --make Main [1 of 1] Compiling Mai

Haskell How to use Hcodecs to write wav files

I am trying to get started playing a bit around with sound in haskell. I imagine that i will ind up with a list representing the soundwave. My problem is taking this list, and turning it into the Audio type from the Hcodecs library, so that I can use the library to create a wave file. So the question is: How to I go from a list to an Audio?

Installing Haskell on Ubuntu 12

I skimmed some tutorials about installing Haskell on Ubuntu. They basically told about Ubuntu 11 and mentioned that it took a lot of effort. I found nothing about installing Haskell on Ubuntu 12. Is there any tutorial or something about how to do it? Is there an installer for Ubuntu 12 x64?

Haskell Compile SDL with cabal in MinGW

I’m trying to install SDL within cabal for Haskell, in MinGW, but I got some problems. cabal can’t find the C library, and I don’t know why. Here some info: I have downloaded both the dev and runtime library of the SDL1.2 ; For the dev version, I make native it: it’s installed in /usr/include/SDL and /usr/lib ; I tried a cabal install SDL, it failed because it can’t find both the header file and the lib ; Then, I give it another try with cabal install SDL --extra-include-dirs=/usr/include/SDL

Haskell How do I calculate the sum from my functions?

I have a file (points.txt) with some Cartesian coordinates defined: A 1.0 2.2 B 2.1 3.0 C 3.5 4.0 D 4.0 5.0 I have a second file (routes.txt) with routes defined based on the points from points.txt. route1 ACDB route2 ABC I need to find the length of each route. So far I have a calculation of the distance between two points, like this: type Point = (String, Float, Float) distance_points :: IO () distance_points = do s <- readFile "pontos.txt" putStr "Fom: "

Haskell Multiple independent ST/State monads within a Monad Transformer (RandT)...complicated wrapping/unwrapping

Just learning how to get a deeper intuitive grasp of monads and transformers; a lot of things that might seem obvious are still kind of tricky to me haha. So I have a computation that lives in the Rand monad, but inside it, there is another "sub-computation" (or multiple) that lives inside an ST monad (or State monad, for all it matters ... ST only for performance but I think State works just as well in this context). The entire computation doesn't need to be inside the ST monad...and this sub

Haskell IO computation order

I have learned Haskell for some time, but IO monad yet scared me. I have a code main = do putStrLn "First computation starts" let firstResult = foo -- foo is a pure function putStrLn "Second computation starts" let secondResult = bar foo -- bar is too pure function writeFile secondResult And see "First computation starts" "Second computation starts" and then program will be doing. I know that there is laisy computation, and really computation starts when writeFile exec

Haskell cabal install: missing C library iw

I'm running Fedora 19 x64, and I'm trying to install xmobar via cabal install. After installing a bunch of dependencies, I'm stuck at cabal: Missing dependency on a foreign library: * Missing C library: iw I can't find anything about this iw library and I'm a bit lost at how to continue. I've got all of the standard c libs installed, as far as I can tell. sudo yum install glibc-common glibc glibc-devel glibc-headers glibc-utils glibc-devel glib2-devel gcc-c++ gcc Loaded plugins: auto-

Haskell Representing Integers as Functions (Church Numerals?)

Given the following function definition and assuming similar definitions for all positive integers give the type definition and code for a function called plus that will take as arguments two such functions representing integers and return a function that represents the sum of the two input integers. E.g. (plus one two) should evaluate to a function that takes two arguments f x and returns (f(f(f x))). one f x = f x two f x = f (f x) three f x = f (f (f x))) etc. I am new to functional progr

Averaging error Haskell

I have created two functions below, one which gets the films of the director and another which gives the average. The function which is giving me the problem is the directorAverage stating i have too few arguments. Am i missing something that is needed? import Data.List import Text.Printf import Data.Ord import Data.Char type Rating = (String, Int) type Title = String type Director = String type Year = Int type Film = (Title, Director, Year,[Rating]) testDatabase :: [Film] testDatabase = [(

Sublists in order in haskell

All I wanna do is really simple but it seems hard for me to implement. I want a function in haskell with this behavior. orderedsubs [2,5,3,4] = [[],[2],[2,5],[2,5,3],[2,5,3,4]] Initially I thought about removing last element and put it to the list and repeat the process with the previously created list but once it's stored, it's gone. I don't care if the order of the sublists is different, but I want these specific sublists. So, any ideas? Thanks in advance.

Haskell What is groupBy supposed to do?

I wrote something using Data.List.groupBy. It didn't work as expected so I end up writting my own version of groupBy : after all I'm not sure that the Data.List one is supposed to do (there is no real documentation). Anyway my tests passed with my version of groupBy whereas it fails with the Data.List. I found (thanks quickcheck) a case where the two function behaves differently, and I still don't understand why there is a difference between the two versions. Is the Data.List version buggy or

Haskell Riak driver: Making a simple 'put' operation

I am trying to introduce myself to Riak with Haskell driver and I am stuck with a simple put operation. I am confused with the signature of the put function. and there isn't a single example anywhere out there. So with this signature: put :: (FromJSON c, ToJSON c, Resolvable c) => Connection -> Bucket -> Key -> Maybe VClock -> c -> W -> DW -> IO (c, VClock) I have a couple of questions. What is a Maybe VClock? Do I have to generate it somehow or is it enough

Haskell Counting of algebraic data types

I'm reading/listening to Chris Taylor's presentation on algebraic data types. http://chris-taylor.github.io/blog/2013/02/10/the-algebra-of-algebraic-data-types/ And there's a section on function types. Specifically the example data Bool = True | False data Trio = First | Second | Third Given the law a -> b == B^A Given Trio -> Bool should equal 8 Why 8 and not 6 via multiplication? If I'm understanding this correctly, the concrete combinations should be First -> Tr

Haskell Replace nested pattern matching with "do" for Monad

I want to simplify this code {-# LANGUAGE OverloadedStrings #-} import Data.Aeson import Network.HTTP.Types import Data.Text getJSON :: String -> IO (Either String Value) getJSON url = eitherDecode <$> simpleHttp url -------------------------------------------------------------------- maybeJson <- getJSON "abc.com" case maybeJson of Right jsonValue -> case jsonValue of (Object jsonObject) -> case (HashMap.lookup "key123" jsonObject) of (Just (Stri

Haskell Efficient Rational Resampling with lazy semantics

To change the sampling rate of a signal, one needs to upsample , filter, then downsample. Doing this naively means inserting zeros into the input signal, correlating with a filter's impulse response, then discarding all but every nth sample of the convolution. The problem with the naive approach is that there is a lot of useless computation. When convolving with the filter, most of the filter taps are multiplied by zero, and computing the value of samples that will be discarded in the downsampl

Haskell Check if Int `mod` every element of a list == 0

I'm writing a (Literate) Haskell code that bruteforces the lcm (least common multiple) of a list of Ints. I already thought about a strategy, but I'm not that good with Haskell syntax and don't know a lot of functions. This is the function so far: > bruteforceLCM :: [Int] -> Int -> Int > bruteforceLCM xs n = if EVERYELEMENTOFTHELIST `mod` n == 0 > then n > else (bruteforceLCM xs (n+1)) Where xs is the list of all Ints and n is

Haskell No instance for (Floating Int) arising from a use of `sqrt`

I'm doing some basic work in Haskell and don't understand why this isn't compiling. Here's the error: shapes.hs:35:11: No instance for (Floating Int) arising from a use of `sqrt' In the expression: sqrt (hd * hd + vd * vd) In an equation for `d': d = sqrt (hd * hd + vd * vd) In the expression: let hd = xc - x vd = yc - y d = sqrt (hd * hd + vd * vd) in if d <= r then True else False Related code: type Point = (Int,Int) data Figure = Rect

Strange Haskell expression with type Num ([Char] -> t) => t

While doing some exercises in GHCi I typed and got the following> ghci> (1 "one") <interactive>:187:1: No instance for (Num ([Char] -> a0)) arising from a use of ‘it’ In a stmt of an interactive GHCi command: print it which is an error, howeve if I ask GHCi for the type of the expression it does not give any error: ghci> :type (1 "one") (1 "one") :: Num ([Char] -> t) => t What is the meaning of (1 "one")? Why does this expression gives an error, but GHCi tells it

Haskell error: "No instance fo (Eq Time) arising from a use of '=='

I'm pretty new to Haskell and I don't get why I can't compare those 2 variables. I have this function: nextMinute :: Date -> Time -> DateTime nextMinute date time = if time == Time 23 59 then DateTime (tomorrow date) newDay else DateTime date (timeSucc time) I get this error message: Time.hs:88:32: No instance for (Eq Time) arising from a use of ‘==’ In the expression: time == Time 23 59 In the expression: if time == Time

Haskell Multiparameter typeclasses and illegal instance declarations

I made a version of the Convertible class like so: class Convertible a b where convert :: a -> b instance (Convertible a b, Functor f) => Convertible (f a) (f b) where convert = fmap convert However, I found it annoying that I would have to make a new instance if I ever wanted to string two conversions together. So I tried adding this: instance (Convertible a b, Convertible b c) => Convertible a c where convert = convert . convert The compiler complained with this: Variabl

decoding haskell pcap header

I am trying to get more information out of PktHdr in the pcap Haskell library. But it seems like the type does not give me much. How can I get things like source address, destination address and port? Do I have to translate the bytes myself, or am I not reading the doc for this library correctly?

How to filter unwanted words in a text file Haskell

I'm trying to write a program in Haskell that can filter out unwanted keywords from a text document. The text document contains information about persons, for example name, age and city, and I want to filter out all of the information associated to those persons who dose not fulfill the keyword. The database looks something like this: "Eric" 27 "London" "Josefine" 34 "Stockholm" "Hans" 50 "London" So if the keyword is "London", I want the following output: "Eric" 27 "London" "Hans" 50 "Lon

Haskell Where do yesod binaries expect to find the config folder?

I'm creating a docker container to run haskell binary. The binary in question is a website built with yesod. When the container starts up it looks promising but then fails with: config/client_session_key.aes: openBinaryFile: does not exist (No such file or directory) Steps to recreate The Dockerfile for the binary is very basic. It looks like this: FROM haskell:7.10.3 MAINTAINER Garry Cairns ENV REFRESHED_AT 2015-09-05 RUN ["apt-get", "-y", "update"] RUN ["apt-get", "-y", "install", "libpq

Haskell Importing modules for testing

I'm having some trouble importing a module for testing. I want to import Load in TestLoad in order to test it. I've tried adding the source directory to hs-source-dirs and both the package nsga and the module Load to build-depends in the cabal file for the testing package, but GHC still complains Could not find module Load when I attempt to import Load in TestLoad.hs. I'm also curious about how to structure the tests and how to name the files. Is the approach below correct? Directory structure

Haskell Prefix lenses for a type

I have the following data declared: data Something = Something { self :: String , id :: String , description :: Maybe String , name :: String } deriving (Generic, Show) instance FromJSON Something makeLensesFor [ ("self", "somethingSelf") , ("id", "somethingId") , ("description", "somethingDescription") , ("name", "somethingName") ] ''Something Is it possible to automate the lenses creation as the naming convention is foll

Haskell Function pattern match depending on data argument

First of: sorry for the ambigous question title... Second: I am a complete beginner... I have a very simple data type called Task. A Task had a price, an amount and a unit. The unit can be days or hours. I want to calculate the total amount and total price for a list of Tasks. For the price there is no issue, I multiply each price with the amount for the given task and it adds up. But for the amount I am stuck. I cannot easely fold a list of hours and days. Say I have a task with 1 hour and o

Haskell How to modify cabal config file on windows

I am installing Haskell on my desktop, which is windows system. I follow the instruction. It says: Modify your cabal config file (you can verify the location by running "cabal user-config init") to contain the following lines: extra-prog-path: C:\Program Files\Haskell Platform\8.0.2\msys\usr\bin extra-lib-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\lib extra-include-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\include I tried to call "cabal user-config init" in command prompt,

Haskell overridePackages of local nixpkgs' config to add new packages

i'm looking for enlightenment on how to do the best way on my situation as follows: I have a nixpkgs folder on my project, which I download from other repo. It located on my theproject/front-plat/default.nix then the code is look like this. { nixpkgsFunc ? import ./nixpkgs }: let nixpkgs = nixpkgsFunc ({ config = { ... }; lib = {...}; etc. In my theproject/release.nix I want to add a new packages which will be used for my built using the nixpkgs' front-plat. So the code looks like this. { fr

Why this haskell code cannot be compiled

I was trying to compile a haskell game code, this code generates three thread, one for infinite loop, one for collecting user's interaction, one for triggering the events. However, the code cannot be compiled and I don't know why. Here's the code: module Main where import Control.Concurrent import Control.Monad import System.IO import System.Random import Text.Printf data Msg = C Char | Time data Event = C Char | Time Char main :: IO () main = do hSetBuffering stdout NoBuffering hSetBuf

Haskell Persistent Database Primary Key

When using the following code, I don't want to use the default database key. Intead, I plan to generate a hashcode from a piece of information and use it as a key. How should I use such a key? share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Person name String age Int Maybe deriving Show BlogPost title String authorId PersonId deriving Show |]

Haskell "(.|.)" syntax

What does this syntax mean? (in the context of module declaration) Example: module XMonad ( module XMonad.Main, module XMonad.Core, module XMonad.Config, module XMonad.Layout, module XMonad.ManageHook, module XMonad.Operations, module Graphics.X11, module Graphics.X11.Xlib.Extras, (.|.), MonadState(..), gets, modify, MonadReader(..), asks, MonadIO(..) ) where Can't find anything using search engines.

Monotonicity of evaluation in Haskell

Let < denote the semantic approximation order in Haskell. Then the monotonicity of evaluation guarantees that if e1 < e2 then [[e1]] < [[e2]], where e1, e2 are expressions and [[e1]] denotes the evaluation of e1. In the notes I am following this is noted as a very useful property to reason about Haskell programs, but there are no examples given. Can somebody give me one example of such reasoning?

How to profile Haskell after compiler optimizations?

I have a fairly complex and performance-critical Haskell program. I have used cost center profiling to optimize to the point where there are no major remaining hot spots. Furthermore, the program runs about 15x faster with -O2 (and no profiling) than it does with stack build --profile, so I have doubts as to whether the cost center profiler is helping much at all with finding bottlenecks that remain post-optimization. What are my options for finding hot spots that remain after optimization? I a

Haskell Parsing embedded JSON with Aeson

I'm trying to parse embedded JSON of the form { "foo":"bar", "baz":"\{\"somekey\":\"someval\"\}" } with Aeson in Haskell. Here are my types: data BaseType = BaseType { foo :: String, baz :: EmbeddedType } deriving(Show) instance FromJSON BaseType where parseJSON = withObject "BaseType" $ \o -> do foo <- o .: "foo" baz <- o .: "baz" return $ BaseType { foo=foo, baz=baz } data EmbeddedType = EmbeddedType { somekey :: String } instance FromJSON EmbeddedType where

Haskell 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 import Data.Sequence as SQ import Data.Matrix as MT allElementsEqualL :: Eq a => [a] -> Bool allElementsEqualL [] = True allElementsEqualL (x:ns) = all (== x) ns -- allElementsEqualL [1,1,1] -&

Binary to Decimal in Haskell without using recursion or list comprehensions

I am currently working on a homework assignment that requires me to implement a function that converts binary to decimal without using list comprehensions or recursion. I've tried using folds, explicitly using foldr, to implement this, but can't quite get correct results. In a related thread I have found the following bintodec :: [Bool] -> Int bintodec = foldr (\x y -> fromEnum x + 2*y) 0 which seems like a good starting point, but does not seem to produce correct results for me. It s

Not being able to install Random module using cabal? (Haskell)

I'm not being able to Install the random module using cabal. I'm using a macbook so I don't know if the commands are any diferent. Here's what I'm typing on the terminal: cabal install random, this is the message I'm getting: Resolving dependencies... Up to date Warning: You asked to install executables, but there are no executables in target: random. Perhaps you want to use --lib to install libraries instead. I don't know if it makes a difference or not but I'm typing these commands while on

Haskell using map to call function with more than one parameter

Let's say we have the following code representing binary trees where decodeInt searches the tree for an integer: import Text.Show.Functions data BinTree a b = Leaf b | Node a (BinTree a b) (BinTree a b) deriving Show example :: BinTree (Int -> Bool) Char example = Node (\x -> x > 4) (Node (\x -> x * x == x) (Leaf 'g') (Node (\x -> x == 0) (Leaf 'u') (Leaf 'l'))) (Node (\x -> x >= 7) (Leaf 'f') (Leaf 'i')) countInnerNodes :: BinTree a b -> Int countInnerNodes

Haskell Constructive handling of sequence numbers

I am implementing a simple protocol where messages have a sequence number that must increment strictly between messages. To handle this I wrote: newtype SequenceNo = SequenceNo Int64 deriving (Show, Eq) validSequence :: SequenceNo -> SequenceNo -> Bool validSequence (SequenceNo firstS) (SequenceNo secondS) = firstS + 1 == secondS I use it something like this: applyUpdates :: ProtocolState -> UpdateMessage -> Either String ProtocolState applyUpdates oldState upd = if validSeq

Obtaining type information with Template Haskell

I'm currently working on a library that allows the user to specify a list of command specifications as follows: data CommandDef = forall (as :: [*]). Typeable as => CommandDef { argTypes :: Proxy as, commandName :: String, commandStrings :: [String], parsers :: HList (FMap CommandParser as), description :: Maybe String } This list of command specifications can then be passed into a template haskell function genCommands :: [CommandDef] -> Q [Dec] to generate a Command data type

Haskell: Define Show function for a user defined type, which is defined by "type" key word

Let's say I have the type StrInt defined as below type StrInt = (String, Int) toStrInt:: Str -> Int -> StrInt toStrInt str int = (str, int) I want the Show function to work as below: Input: show (toStrInt "Hello", 123) Output: "Hello123" I have tried to define show as below: instance Show StrInt where show (str, int) = (show str) ++ (show int) But that gives me error: Illegal instance declaration for ‘Show StrInt’ (All instance types must be of the form

  1    2   3   4   5   6  ... 下一页 最后一页 共 161 页