takeWhile to test length of nested lists - list

I'm new to Haskell, and trying to do the following:
takeWhile (length < 3) [[1],[1,2],[1..3],[1..4]]. But this gives an error which I believe is because takeWhile would test length < 3 [1] instead of length [1] < 3, which is what would work. Do I to make [[1],[1,2],[1..3],[1..4]] into a list of lengths and then do a takeWhile (< 3) for that list of lengths? Or is there a way to do it by directly testing lengths?

You can compose length and (< 3) to achieve what you want:
takeWhile ((< 3) . length) [[1],[1,2],[1..3],[1..4]]

Related

From list of pairs ((3 . #\J) (5 . #\Q)) to list of strings (("3J") (5Q)) in Scheme

I have a list of pairs ((3. #\K) (5 . #\J)) ... and I would like to create a function in scheme that returns the list as this: ("3K", "5J")...
I've beeing trying but I cannot make it.
This is what I have.
; The deckCards will contain the list of pairs;
; The real Deck will contain the empty list.
(define (deck->strings deckCards realDeck)
(let lenOfItem ([n (my-lenght deckCards)])
(if (= 1 n)
(list (card->string (first deckCards)))
(append realDeck (deck->strings (cdr deckCards) realDeck))))
)
I did try doing with cond but for some reason it doesnt return the list and it seems impossible to append the list to the realDeack before calling itself recursively.
I think I found an approach and it worked. Not sure if it good to use it. However, this prints all the strings from top to boottom in a new line... Will this matter? I think its because I have 48 elements.
(map (lambda (i) (card->string i))
clubs)

List definition by repeated entry/iteration

I want to define the Thue-Morse Sequence (or the fair-sharing sequence) in terms of an initial element, 0, and the rule defining the next section of the list in terms of the entire list up until this point. i.e.
fair 0 = [0]
--fair 1 = [0,1]
--fair 2 = [0,1,1,0]
--fair 3 = [0,1,1,0,1,0,0,1]
fair n = fair (n - 1) ++ map (1-) (fair (n - 1))
This works fine to generate the list up to any predefined length, but it seems ineffective to not just define the entire list at once, and use take if I need a predefined amount.
My first attempt at defining the entire list was fair = 0 : map (1-) fair but of course, this populates the list as it goes, so it doesn't ever (need to) reenter the list (and returns [0,1,0,1,0,1...]). What I want is some way to define the list so that when it reaches a not-yet-defined element in the list, it defines the next 'chunk' by reentering the list only until that point, (rather than the computation 'chasing' the new values as they're produced), so the steps in computing the list would be akin to this procedure:
begin with initial list, [0]
map (1-) over the existing list, producing [1]
append this to the existing list, producing [0,1]
map (1-) over the existing list, producing [1,0]
append this to the existing list, producing [0,1,1,0]
map (1-) over the existing list, producing [1,0,0,1]
append this to the existing list, producing [0,1,1,0,1,0,0,1]
The Wikipedia article I linked above has a helpful gif to illustrate this process.
As I presume you can see, this would continue indefinitely as new elements are needed. However, I can't for the life of me find a way to successfully encode this in a recursive function.
I have tried
reenter f xs = reenter f (xs ++ map f xs)
fair = reenter (1-) [0]
But while the logic seems correct, it hangs without producing anything, probably due to the immediate recursive call (though I thought haskell's lazy evaluation might take care of that, despite it being a rather complex case).
As you noted, you can't do the recursive call immediately - you first need to return the next result, and then recursively call, as in your last try:
Prelude> reenter prev_list = inverted_prev_list ++ reenter (prev_list ++ inverted_prev_list) where inverted_prev_list = map (1-) prev_list
Prelude> f = [0] ++ reenter [0]
Prelude> take 20 f
[0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1]
Following is code in Racket, another functional programming language, using the steps listed in the question.
(define (f n)
(define (invert s) ; sub-function to invert the numbers
(list->string
(for/list ((i (string->list s)))
(if (equal? i #\0) #\1 #\0))))
(let loop ((c 1)
(s "0")) ; starting string is "0"
(if (> c n)
s
(loop (add1 c)
(string-append s (invert s))))))
Testing:
(f 1)
(f 2)
(f 3)
(f 4)
(f 5)
Output:
"01"
"0110"
"01101001"
"0110100110010110"
"01101001100101101001011001101001"
For infinite series:
(define (f)
(define (invert s)
(list->string
(for/list ((i (string->list s)))
(if (equal? i #\0) #\1 #\0))))
(let loop ((s "0"))
(define ss (string-append s (invert s)))
(println ss)
(loop ss)))
To run:
(f)
This may give some ideas regarding a Haskell solution to this problem.

Partitioning a list fairly

I'm sure this is a reasonably common thing but I can't find anything on it (my internet-search-fu is not strong).
I have a function that can group a list into a list of lists of N elements each, with the final sublist being smaller than N if the length of the list is not evenly divisible by N. Some examples:
groupEvery 2 [1,2,3,4] = [[1,2],[3,4]]
groupEvery 4 [1,2,3,4,5,6,7,8,9,10] = [[1,2,3,4], [5,6,7,8], [9,10]]
What I want is to take a list and a positive integer n (in the above examples n could be said to be 2 and 3) and partition it into a new list of n lists. It should work on a list of any type, and produce sublists whose sizes differ as little as possible.
So I would like to have:
fairPartition 3 [1,2,3,4,5,6,7,8,9,10] = [[1,2,3,4], [5,6,7], [8,9,10]]
Or any combination of sublists as long as there are two of length 3 and one of length 4.
A naive attempt using groupEvery:
fairPartition :: Int -> [a] -> [[a]]
fairPartition n xs = groupEvery ((length xs `div` n) + 1) xs
fairPartition 4 [1..10] = [[1,2,3],[4,5,6],[7,8,9],[10]]
but as you can see (3,3,3,1) is not a fair distribution of lengths, and for lists of smaller lengths it doesn't even return the right number of sublists:
# Haskell, at GHCi
*Main> let size = 4 in map (\l -> length . fairPartition 4 $ [1..l]) [size..25]
[2,3,3,4,3,3,4,4,3,4,4,4,4,4,4,4,4,4,4,4,4,4]
I would like a {pseudo,actual}-code function or explanation that is easily translatable to Haskell (the identity translation would be the best!).
Thanks.
You can use the split package's splitPlaces function for this.
import Data.List.Split
fairPartition n xs = case length xs `quotRem` n of
(q, r) -> splitPlaces (replicate r (q+1) ++ replicate (n-r) q) xs

Haskell - Use of Take and Drop to split a list into three parts

So I've came across this function definition that takes a list (xs) and splits it into three parts as an output.
The thing is I'm having difficulty understanding it. I understand the first part which takes n of the list (xs) where n is defined as dividing the length of the list (xs) by 3. But after that I'm not sure entirly sure whats going on.
If anyone could walk me through this function that would be great.
Here is the code:
--SPLITS A LIST INTO THREE PARTS---------------------------------------------------------
split3 xs = (take n xs , take n (drop n xs) , drop (n*2) xs)
where n = length xs `div` 3
The second part drops the first n elements and takes the following n elements.
[------- n -------][------- n -------][------- n -------]
^ ^
dropped taken by `take` ^ dropped by `take`
A concrete example could be a list of [1,2,3], n == 1.
take n (drop n xs)
== take 1 (drop 1 [1,2,3])
== take 1 [2,3]
== 2
The third part drops twice n and takes the rest
[---- 2n -----][---- n -----]
^ ^
dropped taken by `drop`

Haskell: List Boundary

I have a list of doubles(myList), which I want to add to a new List (someList), but once the new list reaches a set size i.e. 25, I want to stop adding to it. I have tried implementing this function using sum but was unsuccessful. Example code below.
someList = [(a)| a <- myList, sum someList < 30]
The way #DanielFischer phrased the question is compatible with the Haskell way of thinking.
Do you want someList to be the longest prefix of myList that has a sum < 30?
Here's how I'd approach it: let's say our list is
>>> let list = [1..20]
we can find the "cumulative sums" using:
>>> let sums = tail . scanl (+) 0
>>> sums list
[1,3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210]
Now zip that with the original list to get pairs of elements with the sum up to that point
>>> zip list (sums list)
[(1,1),(2,3),(3,6),(4,10),(5,15),(6,21),(7,28),(8,36),
(9,45),(10,55),(11,66),(12,78),(13,91),(14,105),(15,120),
(16,136),(17,153),(18,171),(19,190),(20,210)]
Then we can takeWhile this list to get the prefix we want:
>>> takeWhile (\x -> snd x < 30) (zip list (sums list))
[(1,1),(2,3),(3,6),(4,10),(5,15),(6,21),(7,28)]
finally we can get rid of the cumulative sums that we used to perform this calculation:
>>> map fst (takeWhile (\x -> snd x < 30) (zip list (sums list)))
[1,2,3,4,5,6,7]
Note that because of laziness, this is as efficient as the recursive solutions -- only the sums up to the point where they fail the test need to be calculated. This can be seen because the solution works on infinite lists (because if we needed to calculate all the sums, we would never finish).
I'd probably abstract this and take the limit as a parameter:
>>> :{
... let initial lim list =
... map fst (takeWhile (\x -> snd x < lim) (zip list (sums list)))
... :}
This function has an obvious property it should satisfy, namely that the sum of a list should always be less than the limit (as long as the limit is greater than 0). So we can use QuickCheck to make sure we did it right:
>>> import Test.QuickCheck
>>> quickCheck (\lim list -> lim > 0 ==> sum (initial lim list) < lim)
+++ OK, passed 100 tests.
someList = makeList myList [] 0 where
makeList (x:xs) ys total = let newTot = total + x
in if newTot >= 25
then ys
else makeList xs (ys ++ [x]) newTot
This takes elements from myList as long as their sum is less than 25.
The logic takes place in makeList. It takes the first element of the input list and adds it to the running total, to see if it's greater than 25. If it is, we shouldn't add it to the output list, and we finish recursing. Otherwise, we put x on the end of the output list (ys) and keep going with the rest of the input list.
The behaviour you want is
ghci> appendWhileUnder 25 [1..5] [1..5]
[1,2,3,4,5,1,2,3]
because that sums to 21 and adding the 4 would bring it to 25.
OK, one way to go about this is by just appending them with ++ then taking the initial segment that's under 25.
appendWhileUnder n xs ys = takeWhileUnder n (xs++ys)
I don't want to keep summing intermediate lists, so I'll keep track with how much I'm allowed (n).
takeWhileUnder n [] = []
takeWhileUnder n (x:xs) | x < n = x:takeWhileUnder (n-x) xs
| otherwise = []
Here I allow x through if it doesn't take me beyond what's left of my allowance.
Possibly undesired side effect: it'll chop out bits of the original list if it sums to over 25. Workaround: use
appendWhileUnder' n xs ys = xs ++ takeWhileUnder (n - sum xs)
which keeps the entire xs whether it brings you over n or not.