How to group similar items in a list using Haskell?

Whenever possible, reuse library code. import Data.Map sortAndGroup assocs = fromListWith (++) [(k, [v]) | (k, v) <- assocs] Try it out in ghci: *Main> sortAndGroup [(1,”aa”),(1,”cc”),(2,”aa”),(3,”ff”),(3,”gg”),(1,”bb”)] fromList [(1,[“bb”,”cc”,”aa”]),(2,[“aa”]),(3,[“gg”,”ff”])] EDIT In the comments, some folks are worried about whether (++) or flip (++) is the right choice. The documentation doesn’t say which way things get … Read more

What is the monomorphism restriction?

What is the monomorphism restriction? The monomorphism restriction as stated by the Haskell wiki is: a counter-intuitive rule in Haskell type inference. If you forget to provide a type signature, sometimes this rule will fill the free type variables with specific types using “type defaulting” rules. What this means is that, in some circumstances, if … Read more

Why give me error? [closed]

The cause for the error you’re getting here is the use of the name count&remove: identifiers in Haskell have to be either alphanumeric (e.g. count_and_remove) or symbolic (e.g. ==, ++, etc.). Identifiers can’t contain both alphanumeric characters and symbols. But that’s just one problem. You also have a reference to y on line 9 that … Read more

Haskell: Given a list of numbers and a number k, return whether any two numbers from the list add up to k

There are following approaches. 1) Create a list pf pairs which are all combinations [(10,10),(10,15),..,(15,10),(15,3)..]. Now you can use simple any function on this list to check if any pair add up to given number. getCoupleList :: [a]->[(a,a)] getCoupleList [] = [] getCoupleList [x] = [] getCoupleList (x:xs) = map (\y->(x,y)) xs ++ getCoupleList xs … Read more

scrambling txt file using compiler [closed]

Three things that I can see: You have the arguments that you pass to scramble in main the wrong way round. You haven’t defined getContents anywhere. You’re not using getArgs as you require. As you guessed, you only need to get the first argument (as getArgs :: IO [String]); using arg1:_ <- getArgs will indeed … Read more