I'm having trouble with the following exercise :
I'm supposed to reverse all elements in a list except for the first one, the first element of the list must stay in its original position.
Correct Example:
input: rvrsTail [1,2,3,4,5]
output [1,5,4,3,2]
What I have done so far:
rvrsTail :: [x] -> [x]
rvrsTail xs = reverse ( tail xs)
This does reverse the the tail of the list but removes the first element, and since I can't store the first element in a variable I can't seem to understand how to solve this issue.
Erroneous Output:
input: rvrsTail [1,2,3,4,5]
output [5,4,3,2]
Since this is supposed to be a beginner's exercise, the solution should be simple.
When you receive a non-empty list, you must leave the head where it is and append the tail reversed. In other words, you can deconstruct the list into the head and the tail, then reconstruct the list with that head and the reversed tail:
rvrsTail :: [x] -> [x]
rvrsTail [] = []
rvrsTail (listHead : listTail) = listHead : reverse listTail
You are almost there. For making sure that the first element of the list stays as it is, just use pattern matching and remove the tail call:
rvrsTail :: [x] -> [x]
rvrsTail (x:xs) = x:(reverse xs)
Now, note that the above function will throw an exception when tried with empty list. You should handle that case.
Related
Good morning,
I have a problem with coding using ocaml so I had to code a function that take on input list then add to this list an element.
But using this does'nt affect the list1 so how can I do this ?
Thank you.
let rec append list1 element list2 = match list2 with
[]-> list1
| e::l -> if ( element = e ) then e :: list1
else (append list1 element l)
;;
List are immutable in OCaml, you can't change this. You can write a function append that takes a list and returns a new list that appends an element to it.
For example, here is the prepend function that takes a list and an element and returns a new list with the given element prepended to the passed list,
let prepend xs x = x :: xs
The append function is a little bit trickier, since lists in OCaml are singly-linked, so it is easy to prepend but hard to append. To implement the append function you need an intermediate list, let's call it acc for accumulator. You then go through each element of the input list and add it to the accumulator. Since you're prepending, then once the input list is over your accumulator will have all the elements of the input list by in the reversed order, i.e., the first element (aka the head) of the acc list will be the last element of the input list. Now you what is left is to prepend the element that we want to append to the reversed acc list and reverse act. Here is the skeleton code for you
let append xs x =
let rec loop xs acc = match xs with
| ... -> ... in
loop xs []
for example:
My list of lists in Haskell is:
[[1,2,3], [7,6,8], [0,3,4]]
I need all first element of ervery list in list.
How can I get the output [1,7,4] without "map"?
I need a solution with pattern-matching, not this:
list x = map head x
Look at definitions of map and head functions. And then just copy implementations, combining both functions in one. To make it easier, you can just copy map, replacing function, passed to map with head and then use your own head. You can use case <expr> of ... expression to not implement your own head as a separate function. After doing all this stuff, you can probably refactor your function to make it more elegant.
firsts [] = []
firsts [(x:xs)] = [x]
firsts ((x:xs):xss) = x: firsts xss
> firsts [[1,2,3], [7,6,8], [0,3,4]]
[1,7,0]
I'm new to Haskell but this is what I managed to create here.
I used list comprehension and pattern matching.
--Type definition. Not mandatory but recommended.
firstItemOfEveryList :: [[a]] -> [a]
--First pattern. If the list is empty return a empty list.
firstItemOfEveryList [] = []
--Catch all pattern. Receive a list of lists (xxs). For every inner list (xs <- xxs) call the head method (head xs), but only when the inner list is not null or empty (not(null xs).
firstItemOfEveryList xxs = [head xs | xs <- xxs, not(null xs)]
The empty list pattern is a little bit unnecessary, as it just gives the same result that the last catch. Hope it helps.
Another answer using nested pattern matching:
firsts :: [[a]] -> [a]
firsts [] = []
firsts ([]:xss) = error "sublist is empty"
firsts ((x:xs):xss) = x:firsts xss
Good evening everyone, I'm new to haskell. I'm trying to sum up a list of reading a string Unicode values and store them in a list and then sum the integers up.
getLetterUnicodeValue :: Char -> Int
getLetterUnicodeValue l = (ord l) - 64
unicodeValueList :: String -> [Int]
unicodeValueList x = getLetterUnicodeValue (head x) : unicodeValueList (tail x)
total :: [Int] -> Int
total [] = 0
total x = (head x) + (total (tail x))
I got the error of empty list when the string come to the last character and the sum up function cannot successfully execute. Is there any way to stop the function unicodeValueList when it comes to its end.
*** Exception: Prelude.head: empty list
The surest way to avoid this exception is not to use head. Instead you can use pattern matching to get the head and tail of a list:
unicodeValueList (x:xs) = getLetterUnicodeValue x : unicodeValueList xs
total (x:xs) = x + total xs
This way x and xs will only be available when the list is non-empty and it is guaranteed that you never accidentally access the head or tail of an empty list.
Of course now you'll get a warning that the pattern match is incomplete: You don't specify what should happen when the list is empty. Of course this was true before as well, but now that you use pattern matching the compiler can actually see this and warn you about it (whereas the previous code crashed at runtime without any prior warning).
So what should be done when the list is empty? Well, an empty string contains no unicode values, right? So it should return the empty list when the input is empty:
unicodeValueList [] = []
Of course you don't need pattern matching to fix your error. You could just use an if to make sure that you only call head and tail when the list is not empty. But if you do that, the compiler won't be able to verify that your checks are in order. If you use pattern matching and avoid the unsafe head and tail functions completely, you'll never be able to accidentally access the head or tail of an empty list and the compiler will warn you if you ever forget to consider that the list might be empty.
Yep, you just will have to pattern match in unicodeValueList
unicodeValueList :: String -> [Int]
unicodeValueList [] = []
unicodeValueList (x:xs) = getLetterUnicodeValue x : unicodeValueList xs
Note this could be written more nicely as unicodeValueList = map getLetterUnicodeValue. The reason you are getting the error for head is that your recursion had no base case - it keeps trying to recurse, even when it has reached the empty list.
I'm new to F# and I'm trying to write a method split that splits a list into 2 pieces. It takes a tuple with the first element being the number of elements to split and the second element is the list . For example, split (2, [1;2;3;4;5;6]) should return ([1;2], [3;4;5;6]),
This is what I have so far, but for some reason it is returning the second element of the tuple as the original list without the head. I don't understand this because I thought that x::xs automatically makes x the head element and xs the rest of the list, which would mean that each recursive call is taking the tail of the previous list and chopping off the first term.
let rec split = function
|(n, []) -> ([], [])
|(0, xs) -> ([], xs)
|(n, x::xs) -> let temp = x :: fst (split(n-1, xs))
(temp, xs);;
The problem is on this line:
(temp,xs);;
here in your example, xs will always be [2;3;4;5;6] as long as n>0
You need to get the second element of the list with something like
|(n,x::xs) ->
let a,b = split (n-1,xs)
(x::a,b)
I'd like to know how to swap every second element of a list in Haskell.
Example output should look like this:
swap [1,2,3,4,5]
[2,1,4,3,5]
What I have so far is
swap :: [a] -> [a]
swap [] = []
swap (x:xs) = head xs : [x]
but this only swaps the first two elements and any attempt I make to make the function recursive causes errors when I try to load the file that contains the function. How to make it recursive?
You need to grab out 2 elements at a time:
swap [] = []
swap (x:y:rest) = y:x:(swap rest)
swap [x] = [x]
The last line is needed to allow odd-length lists -- it matches a list having length exactly 1, so it doesn't overlap either of the other 2 cases (length 0, and length 2 or more).
In addition to the other quite excellent replies, here is a solution that uses some very handy libraries. First, install split, which provides many very nice ways of splitting up a list. Our strategy for this problem will be to first split your list into chunks of size two, then swap each chunk, then concatenate the result back into a flat list. Here's how the key function works:
Prelude Data.List.Split> chunk 2 [1..11]
[[1,2],[3,4],[5,6],[7,8],[9,10],[11]]
To swap the elements of each chunk, we can simply call reverse. So the final result is:
Prelude Data.List.Split> let swap = concat . map reverse . chunk 2
Prelude Data.List.Split> swap [1..5]
[2,1,4,3,5]
#j_random_hacker's solution is better, however, if you want to see your implementation to completion, you could try this:
swap [] = []
swap (x:[]) = [x]
swap (x:xs) = head xs : x : (swap $ tail xs)
Notice however, the use of head and tail are unnecessary, and pattern matching can make things much cleaner here.
import Data.Function(on)
swap = map snd . concatMap reverse . groupBy ((==) `on` fst) . zip (cycle "aabb")
Don't take my solution too serious, I'm just trying to improve my Haskell-Foo...