List definition by repeated entry/iteration - list

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.

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)

Haskell rotate list of lists

I'm trying to implement the following function in Haskell, its a recursive traversal that receives an Int and a list of lists [[Int]] and shifts the elements of the inner lists to the right without altering the size of the lists. I was able to get a list with the numbers in the right order but I couldn't insert them back into their proper sublists.
shift_right::Int->[[Int]]->[[Int]]
example #1:
shift_right 1 [[1,2,3],[4,5,6]] => [[6,1,2],[3,4,5]]
example #2:
shift_right 3 [[],[1],[2,3],[4,5,6]] => [[],[4],[5,6],[1,2,3]]
Assuming that the empty lists only appear at the beginning and never in the middle then one approach could be, first to find a way to make a single rotation and then to repeat the same action n times for n rotations. I think we can use mapAccumL for this purpose.
m = [[],[1],[2,3],[4,5,6]]
s l = es ++ (rem ++ ls) : lss
where
(rem, (ls:lss)) = mapAccumL shifter [] fs
shifter a bs = ([last bs], a ++ (init bs))
(es,fs) = span (== []) l -- split empties and fulls
λ> s m
[[],[6],[1,2],[3,4,5]]
λ> s [[],[6],[1,2],[3,4,5]] -- carry from previous answer
[[],[5],[6,1],[2,3,4]]
λ> s [[],[5],[6,1],[2,3,4]] -- carry from previous answer
[[],[4],[5,6],[1,2,3]]
So now... since you show no attempt at all, it is your duty to come up with a code that invokes this function (or a part of this function) n times for n rotations Hint: preferablly without concatenating the empties.

Racket - Given two natural numbers returns a list with all the numbers between a and b

My question is:
Given two natural number returns a list with all the numbers between a and b
I tried this...
* (define (intervalo l s)(cond [(= l s)(make-list l)]
[(< l s)]
[(> l s) empty ])) *
When you say "between a and b", do you mean including the lower bound only? including the upper bound only? Or including both?
Let's make a decision and consider a "half open interval" i.e. the lower bound is included but the upper bound isn't
First, think about what kind of Data the function takes in. As the question states — Natural numbers. Now let's formulate the problem as a brief sentence: "list of numbers from l to s, including l but excluding s"
Some examples:
interval from 0 to 0 will yield an empty list
interval from 1 to 3 will result in (list 1 2)
interval from 3 to 1 is...? It's not valid.
[Refinement] An "assumption" needs be added: the upper bound should be less than or equal to the lower bound.
;; Nat Nat -> [Listof Nat]
;; all nats in [l, s) in order
;; ASUMPTION: (<= l s)
(define (intervalo l s)
(if (= l s) '() (cons l (intervalo (+ l 1) s))))
Racket already provides a range function which can be used as a reference implementation for testing.
An explicit error message can be added for a (> l s) case (the if would be converted to a cond): (raise-arguments-error 'intervalo "lower bound greater than upper bound" "lower" l "upper" s)

LISP:How to read numbers from user and store as a list

I am new to lisp. I am trying to read numbers from user and want to store it as a list. For example: if the user enters 1 2 3 4 5, then the list would contain 5 elements (1 2 3 4 5). I tried (parse-integer(read-line) :junk-allowed t) but it returns only the first element. How should I do this? Thanks.
Use read
The simplest option is to ask the user to enter the list (with the parens) and just call (read).
The second option is to put the parens yourself:
(read-from-string (concatenate 'string "(" (read-line) ")"))
safety and security
Note that the power of the Lisp reader can put you in trouble. E.g., if the user types #.(start-ww3) instead of (1 2 3) at your prompt, you might not reach your bomb shelter in time.
This means that you must bind *read-eval* to nil when calling read on text you do not control.
Call parse-integer repeatedly
Finally, you can call parse-integer in a loop
(defun parse-integers (s &optional (start 0))
(loop with num do
(setf (values num start) (parse-integer s :start start :junk-allowed t))
while num collect num))
or recursively:
(defun parse-integers (s &optional (start 0))
(multiple-value-bind (num end)
(parse-integer s :start start :junk-allowed t)
(and num (cons num (parse-integers s end)))))

List difference function

Does any existing programming language, particularly in the Lisp or ML families, have a library function to calculate list difference in the sense of 'first until start of second' - I'm not sure offhand what it should be called exactly - for example, considering strings as lists of characters, if the inputs are:
abcdef
def
Then the output would be
abc
Code in Common Lisp:
CL-USER 1 > (defun fusos (s1 s2)
(let ((pos (search s2 s1)))
(when pos (subseq s1 0 pos))))
FUSOS
CL-USER 2 > (fusos '(a b c d e f) '(d e f))
(A B C)
There's already an accepted answer, but Common Lisp's LDIFF (short for "list difference") is still worth mentioning. It is based on the structure of lists (the cons cells the list is made of) rather than the elements of the list, so the list being "subtracted" has to be the same cons cell as some tail of the list. It's a bit more specific, but it certainly computes a list difference.
CL-USER> (let* ((abcdef '(a b c d e f))
(def (cdddr abcdef)))
(ldiff abcdef def))
(A B C)
Since takeWhile was mentioned in a comment and Haskell has this function, here is how you could achieve the desired result in Haskell:
takeWhile (flip notElem ys) xs
where your example would be
takeWhile (flip notElem "def") "abcdef"
That is, you take elements from the list xs as long as they are not contained in the list ys. As soon as you find an element that is contained in ys (or hit the end of xs) you stop.
In Standard ML it would be:
fun take_while p [] = []
| take_while p (x::xs) =
if p x then x :: take_while p xs
else []
EDIT: Above, I assumed that the specification was that we stop in the first list, as soon as we find an (arbitrary) element of the second list. Hence the use of takeWhile. However, from the OP it is not clear to me what the actual specification is. If it is remove an existing suffix (the second list) from the input (the first list), then the solution is of course different. In Haskell, without thinking about efficiency, we could do:
removeSuffix [] ys = []
removeSuffix xs#(z:zs) ys
| xs == ys = []
| otherwise = z : removeSuffix zs ys