List creation in Erlang - list

From "Erlang Programming" by Cesarini exercise 3-2
As I go through "Erlang Programming" I get weird list creation issues. From exercise 3-2 I wrote two similar functions.
create( 0 ) -> [];
create( N ) when N > 0 -> [ N | create( N-1 ) ].
reverse_create( 0 ) -> [];
reverse_create( N ) when N > 0 -> [ reverse_create( N-1 ) | N ].
so create(3) generates as I'd expect.
exercise3:create(3).
[3,2,1]
but reverse_create does not generate the list I expect.
exercise3:reverse_create(3).
[[[[]|1]|2]|3]
What do I need to change so that reverse_create(3) returns [1,2,3]? Thanks for explaining.

reverse_create returns a list and you using that as head element to create the list which is resulting in nested lists. Try this solution:
reverse_create( 0 ) -> [];
reverse_create( N ) when N > 0 -> reverse_create( N-1 ) ++ [N].
EDIT: A much better implementation would be:
reverse_create2(N) -> reverse_create_helper(N, []).
reverse_create_helper(0, Acc) ->
Acc;
reverse_create_helper(N, Acc) ->
reverse_create_helper(N-1, [N|Acc]).

Normally a function such as reverse_create would be done in a tail-recursive fashion with an accumulator.
reverse_create(N) ->
reverse_create(N, []).
reverse_create(0, Acc) ->
Acc;
reverse_create(N, Acc) when N > 0 ->
reverse_create(N - 1, [N | Acc]).

Of course, you could always do:
reverse_create(N) -> lists:reverse(create(N)).
This would actually run faster. But that obviously isn't the intent of the exercise. :)

I'm reading the same book, so I'm no more expert than you, but this worked for me...
create(0) -> [];
create(N) when N > 0 -> create(N-1) ++ [N].
reverse_create(0) -> [];
reverse_create(N) when N > 0 -> [N|create(N-1)].

This is
reverse_create(0) -> [];
reverse_create(N) ->
list_create_1(1, N, []).
list_create_1(I, N, List) when N >= I ->
list_create_1(I + 1, N, [I | List]);
list_create_1(_, _, List) -> List.

Related

Breaking a list into sublists of a specified size using foldr

I'm taking a functional programming class and I'm having a hard time leaving the OOP mindset behind and finding answers to a lot of my questions.
I have to create a function that takes an ordered list and converts it into specified size sublists using a variation of fold.
This isn't right, but it's what I have:
splitList :: (Ord a) => Int -> [a] -> [[a]]
splitList size xs
| [condition] = foldr (\item subList -> item:subList) [] xs
| otherwise =
I've been searching and I found out that foldr is the variation that works better for what I want, and I think I've understood how fold works, I just don't know how I'll set up the guards so that when length sublist == size haskell resets the accumulator and goes on to the next list.
If I didn't explain myself correctly, here's the result I want:
> splitList 3 [1..10]
> [[1,2,3],[4,5,6],[7,8,9],[10]]
Thanks!
While Fabián's and chi's answers are entirely correct, there is actually an option to solve this puzzle using foldr. Consider the following code:
splitList :: Int -> [a] -> [[a]]
splitList n =
foldr (\el acc -> case acc of
[] -> [[el]]
(h : t) | length h < n -> (el : h) : t
_ -> [el] : acc
) []
The strategy here is to build up a list by extending its head as long as its length is lesser than desired. This solution has, however, two drawbacks:
It does something slightly different than in your example;
splitList 3 [1..10] produces [[1],[2,3,4],[5,6,7],[8,9,10]]
It's complexity is O(n * length l), as we measure length of up to n–sized list on each of the element which yields linear number of linear operations.
Let's first take care of first issue. In order to start counting at the beginning we need to traverse the list left–to–right, while foldr does it right–to–left. There is a common trick called "continuation passing" which will allow us to reverse the direction of the walk:
splitList :: Int -> [a] -> [[a]]
splitList n l = map reverse . reverse $
foldr (\el cont acc ->
case acc of
[] -> cont [[el]]
(h : t) | length h < n -> cont ((el : h) : t)
_ -> cont ([el] : acc)
) id l []
Here, instead of building the list in the accumulator we build up a function that will transform the list in the right direction. See this question for details. The side effect is reversing the list so we need to counter that by reverse application to the whole list and all of its elements. This goes linearly and tail-recursively tho.
Now let's work on the performance issue. The problem was that the length is linear on casual lists. There are two solutions for this:
Use another structure that caches length for a constant time access
Cache the value by ourselves
Because I guess it is a list exercise, let's go for the latter option:
splitList :: Int -> [a] -> [[a]]
splitList n l = map reverse . reverse . snd $
foldr (\el cont (countAcc, listAcc) ->
case listAcc of
[] -> cont (countAcc, [[el]])
(h : t) | countAcc < n -> cont (countAcc + 1, (el : h) : t)
(h : t) -> cont (1, [el] : (h : t))
) id l (1, [])
Here we extend our computational state with a counter that at each points stores the current length of the list. This gives us a constant check on each element and results in linear time complexity in the end.
A way to simplify this problem would be to split this into multiple functions. There are two things you need to do:
take n elements from the list, and
keep taking from the list as much as possible.
Lets try taking first:
taking :: Int -> [a] -> [a]
taking n [] = undefined
taking n (x:xs) = undefined
If there are no elemensts then we cannot take any more elements so we can only return an empty list, on the other hand if we do have an element then we can think of taking n (x:xs) as x : taking (n-1) xs, we would only need to check that n > 0.
taking n (x:xs)
| n > 0 = x :taking (n-1) xs
| otherwise = []
Now, we need to do that multiple times with the remainder so we should probably also return whatever remains from taking n elements from a list, in this case it would be whatever remains when n = 0 so we could try to adapt it to
| otherwise = ([], x:xs)
and then you would need to modify the type signature to return ([a], [a]) and the other 2 definitions to ensure you do return whatever remained after taking n.
With this approach your splitList would look like:
splitList n [] = []
splitList n l = chunk : splitList n remainder
where (chunk, remainder) = taking n l
Note however that folding would not be appropriate since it "flattens" whatever you are working on, for example given a [Int] you could fold to produce a sum which would be an Int. (foldr :: (a -> b -> b) -> b -> [a] -> b or "foldr function zero list produces an element of the function return type")
You want:
splitList 3 [1..10]
> [[1,2,3],[4,5,6],[7,8,9],[10]]
Since the "remainder" [10] in on the tail, I recommend you use foldl instead. E.g.
splitList :: (Ord a) => Int -> [a] -> [[a]]
splitList size xs
| size > 0 = foldl go [] xs
| otherwise = error "need a positive size"
where go acc x = ....
What should go do? Essentially, on your example, we must have:
splitList 3 [1..10]
= go (splitList 3 [1..9]) 10
= go [[1,2,3],[4,5,6],[7,8,9]] 10
= [[1,2,3],[4,5,6],[7,8,9],[10]]
splitList 3 [1..9]
= go (splitList 3 [1..8]) 9
= go [[1,2,3],[4,5,6],[7,8]] 9
= [[1,2,3],[4,5,6],[7,8,9]]
splitList 3 [1..8]
= go (splitList 3 [1..7]) 8
= go [[1,2,3],[4,5,6],[7]] 8
= [[1,2,3],[4,5,6],[7,8]]
and
splitList 3 [1]
= go [] 1
= [[1]]
Hence, go acc x should
check if acc is empty, if so, produce a singleton list [[x]].
otherwise, check the last list in acc:
if its length is less than size, append x
otherwise, append a new list [x] to acc
Try doing this by hand on your example to understand all the cases.
This will not be efficient, but it will work.
You don't really need the Ord a constraint.
Checking the accumulator's first sublist's length would lead to information flow from the right and the first chunk ending up the shorter one, potentially, instead of the last. Such function won't work on infinite lists either (not to mention the foldl-based variants).
A standard way to arrange for the information flow from the left with foldr is using an additional argument. The general scheme is
subLists n xs = foldr g z xs n
where
g x r i = cons x i (r (i-1))
....
The i argument to cons will guide its decision as to where to add the current element into. The i-1 decrements the counter on the way forward from the left, instead of on the way back from the right. z must have the same type as r and as the foldr itself as a whole, so,
z _ = [[]]
This means there must be a post-processing step, and some edge cases must be handled as well,
subLists n xs = post . foldr g z xs $ n
where
z _ = [[]]
g x r i | i == 1 = cons x i (r n)
g x r i = cons x i (r (i-1))
....
cons must be lazy enough not to force the results of the recursive call prematurely.
I leave it as an exercise finishing this up.
For a simpler version with a pre-processing step instead, see this recent answer of mine.
Just going to give another answer: this is quite similar to trying to write groupBy as a fold, and actually has a couple gotchas w.r.t. laziness that you have to bear in mind for an efficient and correct implementation. The following is the fastest version I found that maintains all the relevant laziness properties:
splitList :: Int -> [a] -> [[a]]
splitList m xs = snd (foldr f (const ([],[])) xs 1)
where
f x a i
| i <= 1 = let (ys,zs) = a m in ([], (x : ys) : zs)
| otherwise = let (ys,zs) = a (i-1) in (x : ys , zs)
The ys and the zs gotten from the recursive processing of the rest of list indicate the first and the rest of the groups into which the rest of the list will be broken up, by said recursive processing. So we either prepend the current element before that first subgroup if it is still shorter than needed, or we prepend before the first subgroup when it is just right and start a new, empty subgroup.

Outputting elements from the list except first n elements

How do you write a F# recursive function that accepts a positive integer n and a list xs as input, and returns a list except first n elements in xs?
let rec something n xs = .. something 7 [1..10] = [8; 9; 10]
I don't think that recursion is the most efficient way to solve this problem, but you can do it like this:
let rec something n xs =
if n > List.length xs || n < 0 then failwith "incorrect parameter n - out of range"
else if n = 0 then xs
else something (n-1) (xs |> List.tail)
let res = something 7 [1..10]
open System
Console.WriteLine(res)
//something 7 [1..10] = [8; 9; 10]
The simple answer is to use List.skip ... i.e. [0..10] |> List.skip 5
To reimplement List.skip you'd be looking at something like:
let rec listSkip n list =
match (n, list) with
| 0, list -> list
| _, [] -> failwith "The index is outside the legal range"
| n, _ when n < 0 -> failwith "The index cannot be negative"
| n, _ :: tl -> listSkip (n - 1) tl
As this is recursion is eligible for tail-call optimization, performance should be similar to an explicit loop.
I've avoided an explicit guard checking List.length against n because List.length requires iteration of the entire list ( which we'd have to check each round of the recursion ). Thus it's cheaper just to try and remove n items and fail if we run into an empty list before n reaches 0.

Count non-empty lists in a lists of lists

I am trying to count the number of non-empty lists in a list of lists with recursive code.
My goal is to write something simple like:
prod :: Num a => [a] -> a
prod [] = 1
prod (x:xs) = x * prod xs
I already have the deifniton and an idea for the edge condition:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [[]] = 0
I have no idea how to continue, any tips?
I think your base case, can be simplified. As a base-case, we can take the empty list [], not a singleton list with an empty list. For the recursive case, we can consider (x:xs). Here we will need to make a distinction between x being an empty list, and x being a non-empty list. We can do that with pattern matching, or with guards:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [] = 0
nonEmptyCount (x:xs) = -- …
That being said, you do not need recursion at all. You can first filter your list, to omit empty lists, and then call length on that list:
nonEmptyCount :: [[a]] -> Int
nonEmptyCount = length . filter (…)
here you still need to fill in ….
Old fashion pattern matching should be:
import Data.List
nonEmptyCount :: [[a]] -> Int
nonEmptyCount [] = 0
nonEmptyCount (x:xs) = if null x then 1 + (nonEmptyCount xs) else nonEmptyCount xs
The following was posted in a comment, now deleted:
countNE = sum<$>(1<$)<<<(>>=(1`take`))
This most certainly will look intimidating to the non-initiated, but actually, it is equivalent to
= sum <$> (1 <$) <<< (>>= (1 `take`))
= sum <$> (1 <$) . (take 1 =<<)
= sum . fmap (const 1) . concatMap (take 1)
= sum . map (const 1) . concat . map (take 1)
which is further equivalent to
countNE xs = sum . map (const 1) . concat $ map (take 1) xs
= sum . map (const 1) $ concat [take 1 x | x <- xs]
= sum . map (const 1) $ [ r | x <- xs, r <- take 1 x]
= sum $ [const 1 r | (y:t) <- xs, r <- take 1 (y:t)] -- sneakiness!
= sum [const 1 r | (y:_) <- xs, r <- [y]]
= sum [const 1 y | (y:_) <- xs]
= sum [ 1 | (_:_) <- xs] -- replace each
-- non-empty list
-- in
-- xs
-- with 1, and
-- sum all the 1s up!
= (length . (take 1 =<<)) xs
= (length . filter (not . null)) xs
which should be much clearer, even if in a bit sneaky way. It isn't recursive in itself, yes, but both sum and the list-comprehension would be implemented recursively by a given Haskell implementation.
This reimplements length as sum . (1 <$), and filter p xs as [x | x <- xs, p x], and uses the equivalence not (null xs) === (length xs) >= 1.
See? Haskell is fun. Even if it doesn't yet feel like it, but it will be. :)

Haskell how could I repeat elements in list when I reach the last one element in the list?

I an new to Haskell programming, and I was tending to create a function that can repeat each elements in the list in n times, the problem is when I reach the last one element from the list and I want to return to the first one in the element and do it again, Like
repeat :: Int -> [t] ->[t]
repeat 0 [] = []
repeat n (x:xs)
| n > 0 = x : repeat (n-1) xs
| n < 0 =[]
This only can print the list when n is exactly the same as the size of the list, and there would be error if n > length list
The possible result should be like this:
repeat 6 [1,2,3]
the desired result would be : 1,2,3,1,2,3
what should I edit if I want to get the first element in the list and print again?
Thanks!
As Mark Seemann comment is as simple as taking n elements from the cycle of the list, so
repeat :: Int -> [t] -> [t]
repeat n = take n . cycle
If you want a fully expanded code would be more or less like this:
repeat :: Int -> [t] ->[t]
repeat 0 [] = []
repeat n (x:xs) | n > 0 = x : repeat (n-1) (xs ++ [x])
| otherwise = []
The idea is that each item you consume you append to the list to be processed.
Here you have a live example
A basic alternative is to keep two lists around: one of them is "consumed" through pattern matching, while the other remembers the full list, so that we can start over when needed.
-- requires n >= 0 and nonempty full
repeatAux :: Int -> [t] -> [t] ->[t]
repeatAux 0 _ _full = []
repeatAux n [] full = repeatAux n full full
repeatAux n (x:xs) full = x : repeatAux (n-1) xs full
repeat :: Int -> [t] ->[t]
repeat n _ | n <= 0 = []
repeat _ [] = error "repeat: empty list with n>0"
repeat n full = repeatAux n full full
This can be improved using a local function, so that we can avoid to pass around the full list.
repeat :: Int -> [t] ->[t]
repeat n _ | n <= 0 = []
repeat _ [] = error "repeat: empty list with n>0"
repeat n full = go n full
where
go 0 _ = []
go n [] = go n full
go n (x:xs) = x : go (n-1) xs

Erlang - element and list

I'm new to erlang. I wonder how to write a function which returns the first N elements in a list?
I've tried:
take([],_) -> [];
take([H|T],N) when N > 0 -> take([H,hd(L)|tl(T)], N-1);
take([H|T],N) when N == 0 -> ... (I'm stuck here...)
Any hint? thx
Update: I know there's a function called "sublist" but I need to figure out how to write that function by my own.
I finally figured out the answer:
-module(list).
-export([take/2]).
take(List,N) -> take(List,N,[]).
take([],_,[]) -> [];
take([],_,List) -> List;
take([H|T], N, List) when N > 0 -> take(T, N-1, lists:append(List,[H]));
take([H|T], N, List) when N == 0 -> List.
In Erlang, take is spelled lists:sublist:
L = [1, 2, 3, 4];
lists:sublist(L, 3). % -> [1, 2, 3]
A simple solution is:
take([H|T], N) when N > 0 ->
[H|take(T, N-1)];
take(_, 0) -> [].
This will generate an error if there are not enough elements in the list.
When you use an accumulator as you are doing you do not usually append elements to the end of it as this is very inefficient (you copy the whole list each time). You would normally push elements on to it with [H|List]. It will then be in the reverse order but you then do a lists:reverse(List) to return them in the right order.
take(List, N) -> take(List, N, []).
take([H|T], N, Acc) when N > 0 ->
take(T, N-1, [H|Acc]);
take(_, 0, Acc) -> lists:reverse(Acc).
The accumulator version is tail recursive which is a Good Thing but you need to do an extra reverse which removes some of the benefits. The first version I think is clearer. There is no clear case for either.