How to convert list into nested list in Haskell [duplicate] - haskell

This question already has answers here:
Haskell: Is there an idiomatic way to insert every item in a list into its own list?
(6 answers)
Closed 5 years ago.
How can I turn a list into the nested list such as:
[p,q,q] -> [[p],[q],[q]]
I have tried this way:
return [2,5,6] // But the result is wrong -> [[2,5,6]] (correct would be [[2],[5],[6]] )
Implementation of return looks like this:
return x = [x]

You should apply it every element of the list, not to the list itself, which can be achieved using map:
map (\x -> [x]) [2, 5, 6]
or, equivalently
map (:[]) [2, 5, 6]
or, as you suggest, using return in place of \x -> [x]
map return [2, 5, 6]
Note that in the latter case, the type of the value returned will be (Monad m) => [m a], which is more general than [[a]].

nest [] = []
nest (x:xs) = [x]:nest xs
nest (x:xs) = [x]:nest xs
This splits the input up in to the first value of the array (x) and the rest of the array (xs) and then puts the first value in to an array and puts it at the start of an array where the next value is the next part of the array.
nest [] = []
This terminates the recursion when the list is empty.

A simple list comprehension also works here:
toNested :: [a] -> [[a]]
toNested xs = [[x] | x <- xs]

Related

compare all elements in a list haskell [duplicate]

This question already has answers here:
Is there a function that takes a list and returns a list of duplicate elements in that list?
(4 answers)
Closed 1 year ago.
I have a list with elements that are tuples example:
[(1,2),(3,9),(7,9),(6,4),(1,2),(4,2),(3,9),(1,2)]
I need to compare the first element with the rest of the elements, then then the second item with the rest of the list and so on to return the repeated elements
In this case it should return
(1,2),(1,2),(1,2),(3,9),(3,9)
any idea how to implement it?
I have this implemented
test :: Eq a => [(a,a)] -> [(a,a)]
test [(x,y)] = [(x,y)]
test (x:y:xs)
|((fst (x) == fst (y)) && (snd (x) == snd (y))) = ( [y]) ++ (test (x:xs) )
|otherwise = test (x:xs)
the end condition is bad and always returns the last element of the list
test [(x,y)] = [(x,y)]
And it only compares the first item with the rest of the list but I need to compare the second, the third ... with the rest of the list
first of all if you have two tuples, comparing element wise is the same as using ==. So
-- This code
(fst (x) == fst (y)) && (snd (x) == snd (y))
-- is the same as this code
x == y
Second, notice the recursive nature of your function. Let say you have a way to split your current list into
ys the list of elements equal to the first one
zs the list of elements not equal to the first one
Then ys will be the first part of your final solution. What do you need to do with zs to get the rest of the solution?
Below, theres is a litle guide line you can fill. (this is obviously an assigment, so I'm not going to give you the full answer)
-- if you can't use imports, defined yourself this function.
import Data.List (partition)
test :: Eq a => [a] -> [a]
test [] = []
-- Hint: use recursion
test (x:xs) = undefined -- Notice that if ys is empty, then x wouldn't be a repeated element, so it should be discarted.
where (ys, zs) = partition (== x) xs
-- | |- This is the list of element not equals to x
-- |- This is the list of elements equals to x

Non-exhaustive patterns error when writing recursive list function [duplicate]

This question already has answers here:
Better exception for non-exhaustive patterns in case
(2 answers)
Closed 1 year ago.
In Haskell I want to write a recursive function that for a given list of numbers changes the sign of each element in the sublists:
list = [[1, 3, 6.7, 7.0], [], [1, 8.22, 9, 0]]
multiply (x:xs) = [n * (-1) | n <- x] : multiply xs
but I get an error:
[[-1.0,-3.0,-6.7,-7.0],[],[-1.0,-8.22,-9.0,-0.0]
*** Exception: learning.hs:26:1-48:
Non-exhaustive patterns in function multiply
Can anyone tell me, how can I handle an exception with empty sublists?
It's actually not the empty sublist that's the problem:
ghci> multiply [[1, 2, 3], [4, 5, 6]]
[[-1,-2,-3],[-4,-5,-6]*** Exception: <interactive>:2:1-50: Non-exhaustive patterns in function multiply
You handle the sublists with [n * (-1) | n <-x], and list comprehensions work fine on empty lists; this one will just find no elements to multiply by -1 and so will yield an empty list. And you can see the empty list in the output you quoted; it even goes on producing more output afterwards, which is pretty conclusive that it isn't throwing the exception when it's processing the empty sublist.
So what's the problem? Well, let's look at what the error message actually says: Non-exhaustive patterns in function multiply. What that means is that somewhere your code in the function multiply is doing pattern matching, and the value that is being matched doesn't actually fit any of the patterns you've provided. Well, there's only one place in your entire function that does any pattern matching, and that's multiply (x: xs), so that has to be where the problem is!
Now lists are always either the empty list [] or of the form item : rest_of_list (where the : is the other constructor of the list data type). You have only provided a pattern for the : form, so multiply is definitely going to throw an error if you ever apply it to an empty list. That shows us the problem immediately, even without connecting it to what actually happened in your case (which I'll do in a moment).
How to fix it? You need to say what multiply [] should result in. Generally, when you're writing a recursive function of the lists, you want to start with this form:
func [] = _
func (x : xs) = _
And then fill in the blanks. Occaisionally it's convenient to have other cases like [x] or [x, y] if you need to handle lists with 1 or 2 elements specially. Only very rarely should you leave out the case for [], because if you do your function will definitely throw the exception you're seeing in your question for certain calls.
In this case, multiply just negates all of the values in all of the sublists of its list-of-list argument, so it's easy to see what it should do to an empty list of sublists: just return an empty list. So we would have:
multiply [] = []
multiply (x: xs) = [n * (-1) | n <-x]: multiply xs
(If you're entering this into GHCi rather than in a file, you'll need to use multiline mode to enter that; enter :{ to start multiline mode, then enter all of the lines of your definition, then enter :} to give all of the lines of your code to the compiler at once)
Now, there's one more obvious question. You didn't call multiply [], you called multiply [[1,3,6.7,7.0],[],[1,8.22,9,0]]. So why is it complaining that the argument doesn't match a pattern for an empty list? The original call doesn't, but every time you called your original multiply it calls itself on a smaller list!
It matches [ [1,3,6.7,7.0], [], [1,8.22,9,0] ] against the pattern x : xs, which results in x = [1,3,6.7,7.0] and xs = [ [], [1,8.22,9,0] ]. Then it calls multiply xs.
So in the second call we're matching [ [], [1,8.22,9,0] ] against the pattern x : xs. In this evaluation, x = [] and xs = [ [1,8.22,9,0] ]. and we call multiply xs again with this version of xs.
Now in the third call we match [ [1,8.22,9,0] ] against the pattern x : xs. For this to succeed we have to find both x and xs. The tail of a single element list is the empty list, so x = [1,8.22,9,0] but xs = []. And then we call multply xs again with this version of xs, and that's where the problem is. Now we try to match [] against the pattern x : xs and we can't, but there are no other patterns to try either, so we just get Non-exhaustive patterns in function multiply.
You've done a phenomenal job of handling the recursive step. But as in any programming language, we also need a base case to terminate recursion. Specifically, you need an explicit case for the []. If given [], you want your function to return [], since there's no more work to be done. Consider
multiply :: Num a => [[a]] -> [[a]]
multiply [] = []
multiply (x : xs) = [n * (-1) | n <- x] : multiply xs
The bottom line is exactly what you've already written. You need the second line to handle [] input. The first line is a type signature, which, while not strictly required, is good design in Haskell and will result in better error messages if something goes wrong.
You recurse on the tail of the list, this means that eventually you will call multiply xs with xs an empty list, and since you did not specify a case for the empty list, it will raise an error.
If we thus run the code with a list [1,4] we will make a call with multiply [1,4], this will make a recursive call with multiply [4], and that will make a recursive call with [], and then it can not find a pattern to match with the empty list hence the error. This thus means that your function is missing a base-case. We can implement this as:
multiply :: Num a => [[a]] -> [[a]]
multiply [] = []
multiply (x: xs) = [n * (-1) | n <-x] : multiply xs
We however do not need to make use of recursion, in fact we can implement this with map :: (a -> b) -> [a] -> [b] and negate :: Num a => a -> a:
multiply :: Num a => [[a]] -> [[a]]
multiply = map (map negate)
or we can even generalize this further to work with any Functor:
multiply :: (Foldable f, Foldable g, Num a) => f (g a) -> f (g a)
multiply = fmap (fmap negate)
You can use map with a lambda function wrapping your same list comprehension:
Prelude> list=[[1,3,6.7,7.0],[],[1,8.22,9,0]]
Prelude> map (\x -> [n * (-1) | n <-x]) list
[[-1.0,-3.0,-6.7,-7.0],[],[-1.0,-8.22,-9.0,-0.0]]

Learning Haskell: Making a function that returns a list of elements that only appear once

I'm learning Haskell and I'm trying to make a recursive function that receives a List of integers and returns a List of integers that only appears once in the list ( once :: [Int] -> [Int] ), so, for example, if the input list is [4, 8, 1, 5, 1, 6, 2, 3, 4, 2] the return would be [8, 5, 6, 3] , but I'm having some problems making the code, in how to make this into a recursive function.
I'm also trying to make it using list comprehension, I'm currently reading about it on Learn You A Haskell, but um also stuck, so if you also have an idea on how to make it using list comprehension I would be thankful to see how both implementations work.
Edit:
once [] = []
once (x:xs)
| (x `notElem` xs) = x : once xs
| otherwise = once xs
But as it is my code is doing the exact opposite, is returning me the repeated elements, and when I try to invert the return of the guards it just returns the complete list without the repeated elements, I'm really out of ideas on how to make it return what I want, only the unique elements that apear once in the list.
There are basically three possible cases:
the list is empty, so then we return an empty list;
the list is not empty, and the first item x is an element in the remaining list xs, then we skip that item and filter out all items in the tail when we recurse; and
the list is not empty and the first item x does not appear in the rest of the list xs, in that case we yield x, and recurse on xs.
The function thus looks like:
once :: [Int] -> [Int]
once [] = []
once (x:xs)
| x `elem` xs = …
| otherwise = …
I leave it as an exercise to fill in the … parts. For the second case, you can make use of filter :: (a -> Bool) -> [a] -> [a].

Haskell Matching pattern for lists

I'm very new to Haskell, and I decided to learn it some days ago, thanks to the haskell wikibook.
I'm reading at this moment the matching pattern for lists, but I can't understand the syntax for list.
Here's an example (from the wikibook) :
doubleList :: [Integer] -> [Integer]
doubleList [] = []
doubleList (n:ns) = (2 * n) : doubleList ns
I don't understand the part (n:ns). How should I read it ?
You can read it like this: (head:tail), so if you have [1, 2, 3] and you match it with (x:xs), then x will be bound to the first element in the list, 1, and xs will be bound to the rest of the list, in this case [2, 3].
(:) is an operator with type a->[a]->[a]. This means that it takes an item, and a list of those items, and returns another list of the same items. The output list is formed by prepending the input item to the input list.
Here is how you can use it
1:[2,3]
will return
[1,2,3]
Because the (:) appears on the left hand side of the definition, in your case, you are pattern matching, and the operator is being used to deconstruct the value, rather than build it.
For example, if we have
func (first:rest) = ....
and call it like this
func [1,2,3]
the following values would be assigned
first=1 --notice, this is type a
rest=[2,3] --notice, this is type [a]
Another tip that might help you understand is by looking at the definition of the list data type:
data [] a = [] | a : ([] a)
Note that Haskell makes special syntax rules just for the list type, normally [] is not a valid constructor. This definition is equivalent to
data List a = Empty | Cons a (List a)
Where
[] = Empty
(:) = Cons
You would pattern match on this as
doubleList :: List Int -> List Int
doubleList Empty = Empty
doubleList (Cons n ns) = Cons (2 * n) (doubleList ns)
If written using infix form:
doubleList (n `Cons` ns) = (2 * n) `Cons` doubleList ns
So now hopefully you can see the parallels between the two definitions. Haskell also provides the special syntax rule that
[1, 2, 3, 4] = 1:2:3:4:[]
Since the former is much easier to write and read. In fact, whenever you have a list literal like [1, 2, 3, 4] in your code, the compiler first converts it to 1:2:3:4:[] before converting your code into an executable.

Haskell mapping function to list

I am new to Haskell and I have the following problem. I have to create a list of numbers [f1, f2, f3...] where fi x = x ^ i. Then I have to create a function that applies the fi to a list of numbers. For example if I have a list lis = [4,5,6,7..] the output would be [4^1, 5^2,6^3, 7^4...]. This is what I have written so far :
powers x= [x^y |y<-[1,2,3,4]]
list = [1,2,3,4]
match :: (x -> xs) -> [x] -> [xs]
match f [] = []
match f (x:xs) = (f x) : ( match f xs )
So if I put the list = [1,2,3] the output is [1,1,1,1][2,4,8,16],[3,9,27,81] instead of [1,4,27]
Can you please tell me what is wrong and point me to the right direction?
The first issue is that powers is of type Int -> [Int]. What you really want, I think, is something of type [Int -> Int] -- a list of Int -> Int functions instead of a function that takes an Int and returns a list of Int. If you define powers like so:
powers = [(^y) | y <- [1..4]]
you can use zipWith to apply each power to its corresponding element in the list, like so:
zipWith ($) powers [1,2,3] -- returns [1,4,27]
The ($) applies its left (first) argument to its right (second) argument.
Note that using powers as defined here will limit the length of the returned list to 4. If you want to be able to use arbitrary length lists, you want to make powers an infinite list, like so:
powers = [(^y) | y <- [1..]]
Of course, as dave4420 points out, a simpler technique is to simply use
zipWith (^) [1,2,3] [1..] -- returns [1,4,27]
Your match is the standard function map by another name. You need to use zipWith instead (which you can think of as mapping over two lists side-by-side).
Is this homework?
You are currently creating a list for every input value.
What you need to do is recursively compute the appropriate
power for each input value, like this:
match f [] = []
match f (x:xs) y = (f x y) : (match f xs y+1)
Then, you can call this as match pow [1, 2, 3] 1.
This is equivalent to using zipWith and providing the desired function (pow), your input list ([1, 2, 3]) and the exponent list (a lazy one to infinity list) as arguments.

Resources