Haskell creating my own filtering function - haskell

I'm a new to haskell, I'm trying to create a function that will take a list on integers and returns a list containing two sublists, the first sublist containing the even number and the other containing the odd numbers. I cannot use even, odd or filter functions. i created my own functions as follows
myodd :: Integer -> Bool
myodd n = rem (abs(n)) 2 == 1
myeven :: Integer -> Bool
myeven n = rem (abs(n)) 2 == 0
segregate [] = ([], [])
segregate [x] = ([x], [])
segregate (x:y:xs) = (x:xp, y:yp) where (xp, yp) = segregate xs
im having trouble trying to use the two first functions and use it on the segregated functions. I have more experience in racket and the function I crated looks like this:
(define (myeven? x)
(= (modulo x 2) 0))
(define (myodd? x)
(= (modulo x 2) 1))
(define (segregate xs)
(foldr (lambda (x b)
(if (myeven? x)
(list (cons x (first b)) (second b))
(list (first b) (cons x (second b))))) '(()()) xs))

Here's one good way:
segregate [] = ?
segregate (x:xs)
| myEven x = ?
| otherwise = ?
where (restEvens, restOdds) = segregate xs
You could also use
segregate = foldr go ([], []) where
go x ~(evens, odds)
| myEven x = ?
| otherwise = ?

A simple way is to run through the list twice using each of your hand-rolled functions as a guard predicate:
segregate :: [Integer] -> ([Integer], [Integer])
segregate [] = ([],[])
segregate xs = (evens, odds)
where evens = [x | x <- xs, myeven x]
odds = [x | x <- xs, myodd x]
Note: your question asked for a list of lists but your pattern matching segregate [] = ([],[]) indicated you wanted a tuple so I gave a tuple solution.

If you really need such a function rather than writing it for educational purposes, there is partition in Data.List, so a simple
import Data.List(partition)
wil get you going.
In the educational case, you can still compare your code, once you're done, with the code of partition.

Related

Haskell Basics of Recursion

I'm not exactly sure if I'm even supposed to ask more general, nonspecific questions on this platform, but I'm new to writing Haskell and writing code in general and an in-depth explanation would really be appreciated. I'm very used to the typical method of using loop systems in other languages, but as Haskell's variables are immutable, I've found recursion really difficult to wrap my head around. A few examples from the Haskell Wikibook include:
length xs = go 0 xs
where
go acc [] = acc
go acc (_:xs) = go (acc + 1) xs
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys
[] !! _ = error "Index too large" -- An empty list has no elements.
(x:_) !! 0 = x
(x:xs) !! n = xs !! (n-1)
The first one is kind of self-explanatory, just writing a length function for strings from scratch. The second is like an index search that returns a char at a specified point, and the third I guess kind of transposes lists together.
Despite somewhat knowing what these pieces of code do, I'm having a lot of trouble wrapping my head around how they function. Any and all step-by-step analysis of how these things actually process would be GREATLY appreciated.
EDIT: Thank you all for the answers! I have yet to go through all of them thoroughly but after reading some this is exactly the kind of information I'm looking for. I don't have a lot of time to practice right now, finals soon and all, but during my break and decided to take another crack at recursion with this:
ood x
|rem x 2 == 1 = ood (x-1)
|x <= 0 = _
|otherwise = ood (x-2)
I wanted to attempt to make a small function that prints every odd number starting from x down to 1. Obviously it does not work; it simply only prints 1. I believe it does hit every odd number on the way down, it just does not display it's answers intermittently. If any one of you could take my own attempt at code and show me how to create a successful recursion function it would really help me a lot!
Let's look at how one might construct two of these.
zip
We'll start with zip. The purpose of zip is to "zip" two lists into one. The name comes from the analogy of zipping two sides of a zipper together. Here's an example of how it functions:
zip [1,2,3] ["a", "b", "c"]
= [(1,"a"), (2,"b"), (3,"c")]
The type signature of zip (which is typically the first thing you'd write) is
zip :: [a] -> [b] -> [(a, b)]
That is, it takes a list of elements of type a and a list of elements of type b and produces a list of pairs with one component of each type.
To construct this function, let's go for standard Haskell pattern matching. We have four cases:
The first list is [] and the second list is [].
The first list is [] and the second list is a cons (constructed using :).
The first list is a cons and the second list is [].
The first list is a cons and the second list is also a cons.
Let's work out each of these.
zip [] [] = ?
If you zip together two empty lists, you have no elements to work with, so surely you get the empty list.
zip [] [] = []
In the next case, we have
zip [] (y : ys) = ?
We have an element, y, of type b, but no element of type a to pair it with. So we can only construct the empty list.
zip [] (y : ys) = []
The same happens in the other asymmetrical case:
zip (x : xs) [] = []
Now we get to the interesting case of two conses:
zip (x : xs) (y : ys) = ?
We have elements of the right types, so we can make a pair, (x, y), of type (a, b). That's the head of the result. What's the tail of the result? Well, that's the result of zipping the two tails together.
zip (x : xs) (y : ys) = (x, y) : zip xs ys
Putting all these together, we get
zip [] [] = []
zip [] (y : ys) = []
zip (x : xs) [] = []
zip (x : xs) (y : ys) = (x, y) : zip xs ys
But the implementation you gave only has three cases! How's that? Look at what the first two cases have in common: the first list is empty. You can see that whenever the first list is empty, the result is empty. So you can combine these cases:
zip [] _ = []
zip (x : xs) [] = []
zip (x : xs) (y : ys) = (x, y) : zip xs ys
Now look at what's now the second case. We already know that the first list is a cons (because otherwise we'd have taken the first case), and we don't need to know anything more about its composition, so we can replace it with a wildcard:
zip [] _ = []
zip _ [] = []
zip (x : xs) (y : ys) = (x, y) : zip xs ys
That's produces the zip implementation you copied. Now it turns out that there's a different way to combine the patterns that I think explains itself a bit more clearly. Reorder the four patterns like this:
zip (x : xs) (y : ys) = (x, y) : zip xs ys
zip [] [] = []
zip [] (y : ys) = []
zip (x : xs) [] = []
Now you can see that the first pattern produces a cons and all the rest produce empty lists. So you can collapse all three of the rest, producing the nicely compact
zip (x : xs) (y : ys) = (x, y) : zip xs ys
zip _ _ = []
This explains what happens when both lists are conses, and what happens when that's not the case.
length
The naive way to implement length is very direct:
length :: [a] -> Int
length [] = 0
length (_ : xs) = 1 + length xs
This will give you correct answers, but it's inefficient. When evaluating the recursive call, the implementation needs to keep track of the fact that once it's done, it needs to add 1 to the result. In practice, it likely pushes the 1+ onto some sort of stack, makes the recursive call, pops the stack, and performs the addition. If the list has length n, the stack will reach size n. That's not great for efficiency. The solution, which the code you copied obscures somewhat, is to write a more general function instead.
-- | A number plus the length of a list
--
-- > lengthPlus n xs = n + length xs
lengthPlus :: Int -> [a] -> Int
-- n plus the length of an empty list
-- is n.
lengthPlus n [] = n
lengthPlus n (_ : xs) = ?
Well,
lengthPlus n (x : xs)
= -- the defining property of `lengthPlus`
n + length (x : xs)
= -- the naive definition of length
n + (1 + length xs)
= -- the associative law of addition
(n + 1) + length xs
= -- the defining property of lengthPlus, applied recursively
lengthPlus (n + 1) xs
So we get
lengthPlus n [] = n
lengthPlus n (_ : xs) = lengthPlus (n + 1) xs
Now the implementation can increment the counter argument on each recursive call instead of delaying them till afterwards. Well ... pretty much.
Thanks to Haskell's call-by-need semantics, this isn't guaranteed to run in constant memory. Suppose we call
lengthPlus 0 ["a","b"]
This reduces to the second case:
lengthPlus (0 + 1) ["b"]
But we haven't actually demanded the value of the sum. So the implementation could defer that addition work, creating a chain of deferrals that's just as bad as the stack seen earlier! In practice, the compiler is clever enough that it will work out how to do this right when optimizations are enabled. But if you don't want to rely on that, you can give it a hint:
lengthPlus n [] = n
lengthPlus n (_ : xs) = n `seq` lengthPlus (n + 1) xs
This tells the compiler that the integer argument actually has to be evaluated. As long as the compiler isn't being intentionally obtuse, it will be sure to evaluate it first, clearing up any deferred additions.
I'm not sure exactly which part you're confused by. Perhaps you're just overthinking this? Let's walk through zip slowly.
For arguments' sake, let's say we want to execute zip [1, 2, 3] ['A', 'B', 'C']. What do we do?
We have zip [1, 2, 3] ['A', 'B', 'C']. What now?
The first line ("equation") of the definition of zip says
zip [] _ = []
Is our first argument an empty list? No, it's [1, 2, 3]. OK, so skip this equation.
The second equation of zip says
zip _ [] = []
Is our second argument an empty list? No, it's ['A', 'B', 'C']. So ignore this equation too.
The last equation says
zip (x:xs) (y:ys) = (x, y) : zip xs ys
Is our first argument a non-empty list? Yes! It's [1, 2, 3]. So the first element becomes x, and the rest become xs: x = 1, xs = [2, 3].
Is our second argument a non-empty list? Again, yes: y = 'A', ys = ['B', 'C'].
OK, what do we do now? Well, what the right-hand size says. If I put in some extra brackets, the right-hand side basically says
(x, y) : (zip xs ys)
So we're constructing a new list, which starts with (x, y) (a 2-tuple) and continues with whatever zip xs ys is. So our output is (1, 'A') : ???.
What is the ??? part? Well, it's like we executed zip [2, 3] ['B', 'C']. Go back to the top, walk through again the same way as before. You'll find that this outputs (2, 'B') : ???.
Now we started with (1, 'A') : ???. If we replace that with the thing we just got, we now have (1, 'A') : (2, 'B') : ???.
Take this one step further and we have (1, 'A') : (2, 'B') : (3, 'C') : ???. Here the ??? part is now zip [] []. It should be clear that the first equation says this is [], so our final result is
(1, 'A') : (2, 'B') : (3, 'C') : []
which can also be written as
[(1, 'A'), (2, 'B'), (3, 'C')]
You probably already knew that was what the answer would eventually be. I hope now you can see how we get that answer.
If you understand what the three equations make zip do at each step, we can summarise the process like this:
zip [1, 2, 3] ['A', 'B', 'C']
(1, 'A') : (zip [2, 3] ['B', 'C'])
(1, 'A') : (2, 'B') : (zip [3] ['C'])
(1, 'A') : (2, 'B') : (3, 'C') : (zip [] [])
(1, 'A') : (2, 'B') : (3, 'C') : []
If you're still confused, try to put your finger on exactly what part confuses you. (Yeah, easier said than done...)
The key to recursion is to stop worrying about how your language provides support for recursion. You really only need to know three things, which I'll demonstrate using zip as the example.
How to solve the base case
The base case is zipping two lists when one is empty. In this case, we simply return an empty list.
zip _ [] = []
zip [] _ = []
How to break a problem into one (or more) simpler problem(s).
A non-empty list can be split into two parts, a head and a tail. The head is a single element; the tail is a (sub)list. To zip together two lists, we "zip" together the two heads using (,), and we zip together the two tails. Since the tails are both lists, we already have a way to zip them together: use zip!
(As a former professor of mine would say, "Trust your recursion".)
You might object that we can't call zip because we haven't finished defining it yet. But we aren't calling it yet; we are just saying that at some point in the future, when we call this function, the name zip will be bound to a function that zips two lists together, so we'll use that.
zip (x:xs) (y:ys) = let h = (x,y)
t = zip xs ys
in ...
How to put the pieces back together.
zip needs to return a list, and we have our head h and tail t of the new list. To put them together, just use (:):
zip (x:xs) (y:ys) = let h = (x,y)
t = zip xs ys
in h : t
Or more simply, zip (x:xs) (y:ys) = (x,y) : zip xs ys
When explaining recursion, it's usually simplest to start with the base case. However, the Haskell code is sometimes simpler if you can write the recursive case first, because it lets us simply the base case.
zip (x:xs) (y:ys) = (x,y) : zip xs ys
zip _ _ = [] -- If the first pattern match failed, at least one input is empty
Taking a step further back, let's introduce the only recursive function you'll ever need:
fix :: (a -> a) -> a
fix f = f (fix f)
fix computes the fixed point of its argument.
The fixed point of a function is the value that, when you apply the function, you get back the fixed point. For instance, the fixed point of the square function square x = x**2 is 1, since square 1 == 1*1 == 1.
fix doesn't look terribly useful, though, since it looks like it just gets stuck in an infinite loop:
fix f = f (fix f) = f (f (fix f)) = f (f (f (fix f))) = ...
However, as we'll see, laziness lets us take advantage of this infinite stream of calls to f.
Ok, how do we actually make use of fix? Consider this nonrecursive version of zip:
zip' :: ([a] -> [b] -> [(a,b)]) -> [a] -> [b] -> [(a,b)]
zip' f (x:xs) (y:ys) = (x,y) : f xs ys
zip' _ _ _ = []
Given two nonempty lists, zip' zips them together by using the help function f that it receives to zip the tails of its inputs. If either input list is empty, it ignores f and returns an empty list. Basically, we've left the hard work to whoever calls zip'. We'll trust them to provide an appropriate f.
But how do we call zip'? What argument can we pass? This is where fix comes in. Look at the type of zip' again, but this time make the substitution t ~ [a] -> [b] -> [(a,b)]:
zip' :: ([a] -> [b] -> [(a,b)]) -> [a] -> [b] -> [(a,b)]
:: t -> t
Hey, that's the type fix expects! What's the type of fix zip'?
> :t fix zip'
fix zip' :: [a] -> [b] -> [(a, b)]
As expected. So what happens if we pass zip' its own fixed point? We should get back... the fixed point, that is, fix zip' and zip' (fix zip') should be the same function. We still don't really know what the fixed point of zip' is, but just for kicks, what happens if we try to call it?
> (fix zip') [1,2] ['a','b']
[(1,'a'),(2,'b')]
It sure looks like we just found a definition of zip! But how? Let's use equational reasoning to figure out what just happened.
(fix zip') [1,2] ['a','b']
== (zip' (fix zip')) [1,2] ['a','b'] -- def'n of fix
== (1,'a') : (fix zip') [2] ['b'] -- def'n of zip'
== (1,'a') : (zip' (fix zip')) [2] ['b'] -- def'n of fix, but in the other direction
== (1,'a') : ((2,'b') : (fix zip') [] []) -- def'n of zip'
== (1,'a') : ((2,'b') : zip' (fix zip') [] []) -- def'n of fix
== (1,'a') : ((2,'b') : []) -- def'n of zip'
Because Haskell is lazy, the last call to zip' doesn't need to evaluate fix zip', because its value is never used. So fix f doesn't need to terminate; it just needs to provide another call to f on demand.
And in then end, we see that our recursive function zip is simply the fixed point of the nonrecursive function zip':
fix f = f (fix f)
zip' f (x:xs) (y:ys) = (x,y) : f xs ys
zip' _ _ _ = []
zip = fix zip'
Let's briefly use fix to define length and (!!) as well.
length xs = fix go' 0 xs
where go' _ acc [] = acc
go' f acc (_:xs) = f (acc + 1) xs
xs !! n = fix (!!!) xs n
where (!!!) _ [] _ = error "Too big"
(!!!) _ (x:_) 0 = x
(!!!) f (x:xs) n = f xs (n-1)
And in general, a recursive function is just the fixed point of a suitable nonrecursive function. Note that not all functions have a fixed point, though. Consider
incr x = x + 1
If you try to call its fixed point, you get
(fix incr) 1 = (incr (fix incr)) 1
= (incr (incr (fix incr))) 1
= ...
Since incr always needs its first argument, the attempt to calculate its fixed point always diverges. It should be obvious that incr has no fixed point, because there is no number x for which x == x + 1.
Here’s a nice trick to show how to convert normal imperative loops into recursion. Here are the steps:
Make data immutable by not mutating objects (e.g. no x.y = z, only x = x { y = z })
Make variables “nearly immutable” by moving all variable-changes to just before control flow
Change into “goto form”
Work out the set of mutating variables
Add “variable changes” for mutating variables that don’t change at each goto
Replace labels with functions and goto with function (tail) calls
Here is a simple example after step 1 but before anything else (made up syntax)
let sumOfList f list =
total = 0
done = False
while (not done) {
case list of
[] -> done = True
(x : xs) ->
list = xs
total = total + (f x)
}
total
Well this doesn’t really do much other than change variables but there’s one thing we can do for step 2:
let sumOfList f list =
total = 0
done = False
while (not done) {
case list of
[] -> done = True
(x : xs) ->
let y = f x in
list = xs
total = total + y
}
total
Step 3:
let sumOfList f list =
total = 0
done = False
loop:
if not done then goto body else goto finish
body:
case list of
[] ->
done = True
goto loop
(x : xs) ->
let y = f x in
list = xs
total = total + y
goto loop
finish:
total
Step 4: the mutating variables are done, list, and total
Step 5:
let sumOfList f list =
done = False
list = list
total = 0
goto loop
loop:
if not done then
total = total
done = done
list = list
goto body
else
total = total
done = done
list = list
goto finish
body:
case list of
[] ->
done = True
total = total
list = list
goto loop
(x : xs) ->
let y = f x in
done = done
total = total + y
list = xs
goto loop
finish:
total
Step 6:
let sumOfList f list = loop False list 0 where
loop done list total =
if not done
then body done list total
else finish done list total
body done list total =
case list of
[] -> loop True list total
(x : xs) -> let y = f x in loop done list (total + y)
finish done list total = total
We can now clean things up by removing some unused parameters:
let sumOfList f list = loop False list 0 where
loop done list total =
if not done
then body done list total
else finish total
body done list total =
case list of
[] -> loop True list total
(x : xs) -> let y = f x in loop done list (total + y)
finish total = total
And realising that in body done is always False and inlining loop and finish
let sumOfList f list = body list 0 where
body list total =
case list of
[] -> total
(x : xs) -> let y = f x in body list (total + y)
And now we can pull the case into multiple function definitions:
let sumOfList f list = body list 0 where
body [] total = total
body (x : xs) total =
let y = f x in body list (total + y)
Now inline the definition of y and give body a better name:
let sumOfList f list = go list 0 where
go [] total = total
go (x : xs) total = go list (total + f y)
A loop is a function call is a loop. Reentering a loop body with updated loop parameters is the same as reentering a function body in a new recursive call with the updated function parameters. Or in other words, a function call is a goto, and the function name is the label to jump to:
loop_label:
do stuff updating a, b, c,
go loop_label
is
loop a b c =
let a2 = {- .... a ... b ... c ... -}
b2 = {- .... a ... b ... c ... -}
c2 = {- .... a ... b ... c ... -}
in
loop a2 b2 c2
You did say you're comfortable with loops.
Let's give the translations of your example functions in terms of the more primitive construct, case, as defined in the Report:
length xs = go 0 xs
where
go a b = case (a , b) of
( acc , [] ) -> acc
( acc , (_ : xs) ) -> go (acc + 1) xs
so it's the same old plain linear recursion.
Same goes to the other two definitions:
zip a b = case ( a , b ) of
( [] , _ ) -> []
( _ , [] ) -> []
(x : xs , y : ys) -> (x,y) : zip xs ys
(the last one is left as an exercise).

Every n-th element of a list in the form of a list

I went through a post for this problem but I do not understand it. Could someone please explain it?
Q: Find every n-th element of the list in the form of a list start from the n-th element itself.
everyNth :: Int -> [t] -> [t]
everyNth elt = map snd . filter (\(lst,y) -> (mod lst elt) == 0) . zip [1..]
Also, please explain how pattern matching can be used for this problem. That is using
[]->[]
It's easy to use pattern matching to 'select every nth element' for particular cases of n:
every2nd (first:second:rest) = second : every2nd rest
every2nd _ = []
-- >>> every2nd [1..12]
-- [2,4,6,8,10,12]
every3rd (first:second:third:rest) = third : every3rd rest
every3rd _ = []
-- >>> every3rd [1..13]
-- [3,6,9,12]
every4th (first:second:third:fourth:rest) = fourth : every4th rest
every4th _ = []
-- >>> every4th [1..12]
-- [4,8,12]
For the general case, though, we're out of luck, at least with that particular approach. Patterns like those above will need some definite length to be definite patterns. The composed function you mention starts from the thought that we do know how to find every nth member of [1..], namely if it's a multiple of n
multiple n m = m `mod` n == 0
-- >>> filter (multiple 3) [1..12]
-- [3,6,9,12]
So the solution you are trying to understand zips [1..] with the list
index xs = zip [1..] xs
-- >>> index [1..5]
-- [(1,1),(2,2),(3,3),(4,4),(5,5)]
-- >>> index "hello"
-- [(1,'h'),(2,'e'),(3,'l'),(4,'l'),(5,'o')]
Then it filters out just those pairs whose first element is a multiple of n
every_nth_with_index n xs = filter (\(m,a) -> multiple n m) (index xs)
-- >>> every_nth_with_index 3 [1..12]
-- [(3,3),(6,6),(9,9),(12,12)]
-- >>> every_nth_with_index 3 "stackoverflow.com"
-- [(3,'a'),(6,'o'),(9,'r'),(12,'o'),(15,'c')]
Then it gets rid of the ancillary construction, leaving us with just the second element of each pair:
every_nth n xs = map snd (every_nth_with_index n xs)
-- >>> every_nth 3 [1..12]
-- [3,6,9,12]
-- >>> every_nth 3 "stackoverflow.com"
-- "aoroc"
Retracinging our steps we see that this is the same as
everyNth elt = map snd . filter (\(lst,y) -> (mod lst elt) == 0) . zip [1..]
The notorious fold fan strikes again.
everyNth n xs = foldr go (`seq` []) xs n where
go x r 0 = x : r (n - 1)
go _ r k = r (k - 1)
This is very similar to chepner's approach but it integrates the dropping into the recursion. Rewritten without the fold, it's pure pattern matching:
everyNth n = go n where
go k [] = k `seq` []
go 0 (x : xs) = x : go (n - 1) xs
go k (_ : xs) = go (k - 1) xs
With a little cheating, you can define everyNth using pattern matching. Really, we're abstracting out the part that makes pattern matching difficult, as pointed out in Michael's answer.
everyNth n lst = e (shorten lst)
where shorten = drop (n-1) -- here's the cheat
e [] = []
e (first:rest) = first : e (shorten rest)
If you have never seen Haskell before then this takes a bit of explaining.
everyNth :: Int -> [t] -> [t]
everyNth elt = map snd . filter (\(lst,y) -> (mod lst elt) == 0) . zip [1..]
First, note that the type has two arguments, but the definition has only one. This is because the value returned by everyNth is in fact another function. elt is the Int, and the expression in the second line creates a new function that does the job.
Second, note the "." operators. This is an operator that joins two functions together. It is defined like this:
(f . g) x = f (g x)
Here is an equivalent version of the definition with the second argument made explicit:
everyNth elt xs = map snd (filter (\(lst y) -> (mod lst elt) == 0) (zip xs))
When you see a bunch of functions in a chain linked by "." operators you need to read it from right to left. In my second version pay attention to the bracket nesting. zip [1..] xs is the inner-most expression, so it gets evaluated first. It turns a list like ["foo", "bar"] into [(1, "foo"),(2, "bar")]. Then this is filtered to find entries where the number is a multiple of elt. Finally the map snd strips the numbers back out to return just the required entries.

How to process / summarise a list into a "different" list

I think I need something like a fold or maybe a foldt but the examples I've seen, seem to only compress the list into a simple scalar value.
What I need would need to remember and re-use values from previous lines in the list (essentially a "group by" operation)
If my input data looks like:
[["order1", "item1"],["", "item2"],["","item3"],["order2","item4"]]
What is the correct approach to end up with something like:
[["order1",["item1","item2","item3"]],["order2",["item4"]]
ie data Order = Order { id :: Text, items :: [OrderItem]}
What if I wanted a slightly different structure?
[("order1",["item1","item2","item3"]),("order",["item4"])]
ie data OrderTuple = OrderTuple { order :: Order, items :: [OrderItem]}
What if I also wanted to keep a running total of some numeric value from the OrderItem?
edit: Here's the code I'm trying to get working based on Frerich's answer
--testGroupBy :: [[String]] -> [[String]]
testGroupBy :: [[String]] -> [(String, [String])]
testGroupBy z =
--groupBy (\(x:xs) (y:ys) -> x == y || null y) z
groupBy testFunc z
testFunc :: [String] -> [String] -> Bool
testFunc (x:xs) (y:ys) = x == y || null y
Pattern matching is useful here
groupData = foldl acc []
where acc ((r, rs):rss) ("":xs) = (r, rs ++ xs): rss
acc rss (x:xs) = (x, xs): rss
acc _ _ = error "Bad input data"
resultant groups are in reverse order, use reverse if you need.
What if I wanted a slightly different structure?
Simply transform one into other, you can do inside groupData or as separated function.
If you admit initial groups without fst element
groupData = foldr acc []
where acc (x:xs) [] = [(x, xs)]
acc ("":xs) (("", rs):rss) = ("", rs ++ xs): rss
acc (x:xs) (("", rs):rss) = (x, rs ++ xs): rss
acc (x:xs) rss = (x, xs): rss
then
let xs = [["", "item8"],["", "item9"],["order1", "item1"],["", "item2"],["","item3"],["order2","item4"]]
print $ groupData xs
is
[("",["item9","item8"])
,("order1",["item3","item2","item1"])
,("order2",["item4"])]
Instead of looking for a fold-based solution, I'd first try to see whether you can define a function as a composition of higher-level functions (such as map). Let me fire up a ghci session and play abit:
λ: let x = [["order1", "item1"],["", "item2"],["","item3"],["order2","item4"]]
Your "group by" operation actually has an existing name: Data.List.groupBy -- this almost gets us what we need:
λ: import Data.List
λ: let x' = groupBy (\(x:xs) (y:ys) -> x == y || null y) x
λ: x'
[[["order1","item1"],["","item2"],["","item3"]],[["order2","item4"]]]
This groupBy application puts all elements in x into one group (i.e. list) whose first element is equal, or if the second element is empty. This can then get massaged into your desired format (in this case, the second one you proposed with a map):
λ: let x'' = map (\x -> (head (head x), map (!! 1) x)) x'
λ: x''
[("order1",["item1","item2","item3"]),("order2",["item4"])]
Putting it all together:
groupData :: [[String]] -> [(String, [String])]
groupData = map (\x -> (head (head x), map (!! 1) x))
. groupBy (\(x:xs) (y:ys) -> x == y || y == "")
I suppose that with this, building a proper data structure (i.e. something more typesafe than nested lists) should be straightforward.

Haskell - Most frequent value

how can i get the most frequent value in a list example:
[1,3,4,5,6,6] -> output 6
[1,3,1,5] -> output 1
Im trying to get it by my own functions but i cant achieve it can you guys help me?
my code:
del x [] = []
del x (y:ys) = if x /= y
then y:del x y
else del x ys
obj x []= []
obj x (y:ys) = if x== y then y:obj x y else(obj x ys)
tam [] = 0
tam (x:y) = 1+tam y
fun (n1:[]) (n:[]) [] =n1
fun (n1:[]) (n:[]) (x:s) =if (tam(obj x (x:s)))>n then fun (x:[]) ((tam(obj x (x:s))):[]) (del x (x:s)) else(fun (n1:[]) (n:[]) (del x (x:s)))
rep (x:s) = fun (x:[]) ((tam(obj x (x:s))):[]) (del x (x:s))
Expanding on Satvik's last suggestion, you can use (&&&) :: (b -> c) -> (b -> c') -> (b -> (c, c')) from Control.Arrow (Note that I substituted a = (->) in that type signature for simplicity) to cleanly perform a decorate-sort-undecorate transform.
mostCommon list = fst . maximumBy (compare `on` snd) $ elemCount
where elemCount = map (head &&& length) . group . sort $ list
The head &&& length function has type [b] -> (b, Int). It converts a list into a tuple of its first element and its length, so when it is combined with group . sort you get a list of each distinct value in the list along with the number of times it occurred.
Also, you should think about what happens when you call mostCommon []. Clearly there is no sensible value, since there is no element at all. As it stands, all the solutions proposed (including mine) just fail on an empty list, which is not good Haskell. The normal thing to do would be to return a Maybe a, where Nothing indicates an error (in this case, an empty list) and Just a represents a "real" return value. e.g.
mostCommon :: Ord a => [a] -> Maybe a
mostCommon [] = Nothing
mostCommon list = Just ... -- your implementation here
This is much nicer, as partial functions (functions that are undefined for some input values) are horrible from a code-safety point of view. You can manipulate Maybe values using pattern matching (matching on Nothing and Just x) and the functions in Data.Maybe (preferable fromMaybe and maybe rather than fromJust).
In case you would like to get some ideas from code that does what you wish to achieve, here is an example:
import Data.List (nub, maximumBy)
import Data.Function (on)
mostCommonElem list = fst $ maximumBy (compare `on` snd) elemCounts where
elemCounts = nub [(element, count) | element <- list, let count = length (filter (==element) list)]
Here are few suggestions
del can be implemented using filter rather than writing your own recursion. In your definition there was a mistake, you needed to give ys and not y while deleting.
del x = filter (/=x)
obj is similar to del with different filter function. Similarly here in your definition you need to give ys and not y in obj.
obj x = filter (==x)
tam is just length function
-- tam = length
You don't need to keep a list for n1 and n. I have also made your code more readable, although I have not made any changes to your algorithm.
fun n1 n [] =n1
fun n1 n xs#(x:s) | length (obj x xs) > n = fun x (length $ obj x xs) (del x xs)
| otherwise = fun n1 n $ del x xs
rep xs#(x:s) = fun x (length $ obj x xs) (del x xs)
Another way, not very optimal but much more readable is
import Data.List
import Data.Ord
rep :: Ord a => [a] -> a
rep = head . head . sortBy (flip $ comparing length) . group . sort
I will try to explain in short what this code is doing. You need to find the most frequent element of the list so the first idea that should come to mind is to find frequency of all the elements. Now group is a function which combines adjacent similar elements.
> group [1,2,2,3,3,3,1,2,4]
[[1],[2,2],[3,3,3],[1],[2],[4]]
So I have used sort to bring elements which are same adjacent to each other
> sort [1,2,2,3,3,3,1,2,4]
[1,1,2,2,2,3,3,3,4]
> group . sort $ [1,2,2,3,3,3,1,2,4]
[[1,1],[2,2,2],[3,3,3],[4]]
Finding element with the maximum frequency just reduces to finding the sublist with largest number of elements. Here comes the function sortBy with which you can sort based on given comparing function. So basically I have sorted on length of the sublists (The flip is just to make the sorting descending rather than ascending).
> sortBy (flip $ comparing length) . group . sort $ [1,2,2,3,3,3,1,2,4]
[[2,2,2],[3,3,3],[1,1],[4]]
Now you can just take head two times to get the element with the largest frequency.
Let's assume you already have argmax function. You can write
your own or even better, you can reuse list-extras package. I strongly suggest you
to take a look at the package anyway.
Then, it's quite easy:
import Data.List.Extras.Argmax ( argmax )
-- >> mostFrequent [3,1,2,3,2,3]
-- 3
mostFrequent xs = argmax f xs
where f x = length $ filter (==x) xs

How to remove an element from a list in Haskell?

The function I'm trying to write should remove the element at the given index from the given list of any type.
Here is what I have already done:
delAtIdx :: [x] -> Int -> [x]
delAtIdx x y = let g = take y x
in let h = reverse x
in let b = take (((length x) - y) - 1) h
in let j = g ++ (reverse b)
in j
Is this correct? Could anyone suggest another approach?
It's much simpler to define it in terms of splitAt, which splits a list before a given index. Then, you just need to remove the first element from the second part and glue them back together.
reverse and concatenation are things to avoid if you can in haskell. It looks like it would work to me, but I am not entirely sure about that.
However, to answer the "real" question: Yes there is another (easier) way. Basically, you should look in the same direction as you always do when working in haskell: recursion. See if you can make a recursive version of this function.
Super easy(I think):
removeIndex [] 0 = error "Cannot remove from empty array"
removeIndex xs n = fst notGlued ++ snd notGlued
where notGlued = (take (n-1) xs, drop n xs)
I'm a total Haskell noob, so if this is wrong, please explain why.
I figured this out by reading the definition of splitAt. According to Hoogle, "It is equivalent to (take n xs, drop n xs)". This made me think that if we just didn't take one extra number, then it would be basically removed if we rejoined it.
Here is the article I referenced Hoogle link
Here's a test of it running:
*Main> removeIndex [0..10] 4
[0,1,2,4,5,6,7,8,9,10]
deleteAt :: Int -> [a] -> [a]
deleteAt 0 (x:xs) = xs
deleteAt n (x:xs) | n >= 0 = x : (deleteAt (n-1) xs)
deleteAt _ _ = error "index out of range"
Here is my solution:
removeAt xs n | null xs = []
removeAt (x:xs) n | n == 0 = removeAt xs (n-1)
| otherwise = x : removeAt xs (n-1)
remove_temp num l i | elem num (take i l) == True = i
| otherwise = remove_temp num l (i+1)
remove num l = (take (index-1) l) ++ (drop index l)
where index = remove_temp num l 1
Call 'remove' function with a number and a list as parameters. And you'll get a list without that number as output.
In the above code, remove_temp function returns the index at which the number is present in the list. Then remove function takes out the list before the number and after the number using inbuilt 'take' and 'drop' function of the prelude. And finally, concatenation of these two lists is done which gives a list without the input number.

Resources