Check are there lowercase characters in string - string

I need return True or False
True if at least one lowercase character
False no lowercase characters
I tried do it with loop and lambda function
Something like this
(defun check-lower-word (word)
(loop
for ch across word
((lambda (c) (if (lower-case-p c) return T) ch)
)
)
I need False if never worked "if"

With a predefined function, you could use some (manual):
CL-USER> (some #'lower-case-p "AbC")
T
CL-USER> (some #'lower-case-p "ABC")
NIL
There is a similar operation for the loop syntax (manual):
CL-USER> (loop for x across "AbC" thereis (lower-case-p x))
T
CL-USER> (loop for x across "ABC" thereis (lower-case-p x))
NIL
Finally, note that loop always returns nil when the iteration terminates without producing a result, so a less concise use of loop could be:
CL-USER> (loop for x across "AbC" if (lower-case-p x) do (return t))
T
CL-USER> (loop for x across "ABC" if (lower-case-p x) do (return t))
NIL

Code errors
You code is not balanced with respect to parentheses, there is a missing closing parenthesis at the end:
(defun check-lower-word (word)
(loop
for ch across word
((lambda (c) (if (lower-case-p c) return T) ch)
)
) ; <-- closes "(loop"
The syntax error in your loop should have raised an error, it does not make sense to write an expression EXPR directly in (loop for c across w EXPR), there should be a preceding do.
The literal ((lambda (c) E) ch) can be directly written as E where every occurence of the variable c is substituted by ch, namely:
(if (lower-case-p ch) return T)
The use of an intermediate literal lambda brings nothing here.
Also, the above reads as: if ch is lowercase, the value of the if is the value bound to the return variable, otherwise it is T. You are indeed missing parens around (return T). A "one-armed" (if T X) is best written as (when T X).
Another approach
You already have an example with some and loop, you can also use a short-circuiting map:
(defun check-lower-word (word)
(block nil
(map ()
(lambda (c)
(when (lower-case-p c)
(return t)))
word)))
A call to MAP with nil as a first argument means the sequence is iterated for effects and returns nil. For each character in the sequence (list or vector), when the character is lower-case, return T. The return exits the iteration early up to the NIL block.

I did it as
(defun check-lower-word (word)
(block outer
(loop
for ch across word do
(if (lower-case-p ch) (return-from outer T))
)
)
)

Related

Iterating over strings

I have two strings of the same length which differ in exactly one character and I want a string of all the characters which are equal. So basically something like this which evaluates to a string instead of a list of characters:
(loop for a across "abcd"
for b across "abce"
when (char= a b) collect a)
Although performance isn't an issue here, I found it cumbersome to have a (coerce ... 'string) around it.
So I came up with something like
(loop with result = ""
for a across "abcd"
for b across "abce"
when (char= a b)
do (setf result (concatenate 'string result (string a)))
finally (return result))
which does the job but looks not very elegant to me.
(map 'string (lambda (a b) (when (char= a b) a)) "abcd" "abce")
looks nicer but is not working because NIL is not a character when aand bare not equal.
Is there a more elegant idiom to iterate over a string and get a string back?
(loop with result = ""
for a across "abcd"
for b across "abce"
when (char= a b)
do (setf result (concatenate 'string result (string a)))
finally (return result))
Repeated concatenate are not a that good idea for longer strings.
Alternatives:
Loop into a list and coercing to a string
CL-USER 3 > (loop for a across "abcd"
and b across "abce"
when (char= a b) collect a into list
finally (return (coerce list 'string)))
"abc"
Using stream and converting it to a string
CL-USER 4 > (with-output-to-string (*standard-output*)
(loop for a across "abcd"
and b across "abce"
when (char= a b) do (write-char a)))
"abc"
Using an adjustable string
CL-USER 5 > (loop with string = (make-array 0
:element-type 'character
:adjustable t
:fill-pointer 0)
for a across "abcd"
for b across "abce"
when (char= a b) do (vector-push-extend a string)
finally (return string))
"abc"
Another possibility is to use mismatch as in the comment of David Hodge:
CL-USER> (defun f(a b)
(let ((pos (mismatch a b)))
(concatenate 'string (subseq a 0 pos) (subseq a (1+ pos)))))
F
CL-USER> (f "abcdefg" "abcxefg")
"abcefg"
Use map to loop over multiple lists simultaneously
(map 'string #'(lambda (a b) (if (char= a b) a #\Rubout)) "abce" "abcd")
'string coerces resulting list into a string. #\Rubout get's coerced to a zero-length string. #\Backspace would even delete the last character.
Another way (it does not assume anything about elements position)
(defun only-matching (seq1 seq2)
(remove-if-not (lambda (c) (find c seq1)) seq2))
CL-USER> (only-matching "abcd" "abce")
"abc"
CL-USER> (only-matching "abdc" "abec")
"abc"`
or
(coerce
(intersection (coerce "abdc" 'list)
(coerce "abec" 'list))
'string)
which does not preserve order also
Note: remove-if-not is deprecated 'officially'.

extracting a n element from a list with dolist on lisp

I am trying to create a function where it takes a list of letters as parameter and a single letter as a parameter. I want to remove the single letter from the list.
(defun extract-all (lett li)
(let ((new-list nil))
(dolist (letter li new-list)
(if (eql lett letter)
(setf new-list (cons nil new-list))
(setf new-list (cons letter new-list))))))
so if I call the function with (extract-all 'n '(i n t e l l)), I want it to return i t e l l with the n removed.
First of all, you are not removing letters
(characters), but rather
symbols:
(type-of 'n)
==> SYMBOL
Second, there is a standard function remove to do just that:
(remove 'n '(i n t e l l))
==> (I T E L L)
Third, if you remove your "then" clause and reverse the result, you will get what you want:
(defun my-remove (object list)
(let ((new-list nil))
(dolist (element list (nreverse new-list))
(unless (eql object element)
(push element new-list)))))
(my-remove 'n '(i n t e l l))
==> (I T E L L)
Note that there are more ways to skin the cat, e.g.,
(defun my-remove (object list)
(loop for element in list
unless (eql object element)
collect element))
However, it is always best to use the library.
See also Where to learn how to practically use Common Lisp.

How to get the last element of a list and return nil if the element isn't in the list

I would like to get the position of any element in the list and get nil if the element isn't in the list. I did:
(defun myposition (letter list)
(cond
((atom list) nil)
((equal (car list) letter) 0)
((null (car list)) (myposition letter))
(t (1+ (myposition letter (cdr list)))) ) )
(myposition 'k '(g h i j k l)
4
(myposition 'p '(g h i j k l)
nil is not a number
When I replace ((atom list) nil) par ((atom list) 0), I get 6 instead nil
(myposition 'p '(g h i j k l)
6
In your first example, your function will recursively compute 1+1+1+1+0 = 4 to find the correct result.
In your second example, it will run through the whole list, add 1 per (non-matching) element, and finally add nil. So it actually computes 1+1+1+1+1+1+nil, which is incorrect since nil is not a number, hence the error message. If you replace nil by zero, it computes 1+1+1+1+1+1+0 which is wrong.
So your basic problem is that you recursively add 1 and, reaching the end of the list, you would like to throw away what you computed until then. But you have an addition pending which you cannot escape.
The easiest way is to change from a recursive to a tail-recursive solution, which is technically a plain goto. Here the addition is done by incrementing a variable, not by unwinding the call stack, which makes it easy to throw away the result from the previous additions and just return nil because there is no addition pending.
A (tail-)recursive solution could be:
(defun myposition (letter lst)
(labels ((sub (lst pos)
(cond
((null lst) nil)
((equal (car lst) letter) pos)
(t (sub (cdr lst) (1+ pos))))))
(if (atom lst) nil (sub lst 0))))
This will work in Common Lisp, but technically, if your implementation does no tail call optimisation, it might still blow the stack for large lists. That's why Common Lisp prefers iterative solutions, such as using the loop macro:
(defun myposition (letter lst)
(when (consp lst)
(loop for c in lst for i from 0
when (equal c letter) return i)))

LISP - Modify String

I have to write a program that changes a string's vowels, consonants and other symbols into C, V respectively 0. I've done this but I wonder if there is a more efficient and elegant way to do it. Would appreciate input.
(defun string-to-list (string)
(loop for char across string collect char))
(defun is-vowel (char) (find char "aeiou" :test #'char-equal))
(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))
(defun letter-type (char)
(if (is-vowel char) "V"
(if (is-consonant char) "C"
"0")))
(defun analyze-word (word-string)
(loop for char across word-string collect (letter-type char)))
Moreover, I would like to make it a string, how could I do that? Should I define a function that would iterate through the list and make it a string or is it an easier way to do it?
(defun letter-type (char)
(cond ((find char "aeiou" :test #'char-equal) #\V)
((alpha-char-p char) #\C)
(t #\0)))
CL-USER> (map 'string #'letter-type "analyze-word")
"VCVCCCV0CVCC"
Just for the sake of the idea:
(defun multi-replace-if (sequence function &rest more-functions)
(map (type-of sequence)
(lambda (x)
(loop for f in (cons function more-functions)
for result = (funcall f x)
while (eql x result)
finally (return result)))
sequence))
(multi-replace-if "bcdfghjklmnpqrstvwxyz"
(lambda (x) (if (find x "aeiouy") #\v x))
(lambda (y) (declare (ignore y)) #\c))
"cccccccccccccccccccvc"

detecting a palindrome without using reverse

I was thinking a way to create a function that detects a palindrome without using reverse...
I thought I would be clever and do a condition where substring 0 to middle equals substring end to middle. I;ve found out that it only works on words with 3 letters "wow" because "w" = "w". But if the letters are like "wooow", wo doesn't equal ow. What is a way to detect palindrome without using a reverse function?
Hint or solutions might be very helpful
(define (palindrome? str)
(cond
((equal? (substring str 0 (- (/ (string-length str) 2) 0.5))
(substring str (+ (/ (string-length str) 2) 0.5) (string-length str))) str)
(else false)))
Oh and I'm using beginner language so I can't use stuff like map or filter
yes I know this is a very useless function haha
It's possible to solve this problem by messing around with the string's characters in a given index. The trick is to use string-ref wisely. Here, let me give you some hints pointing to a solution that will work with the beginner's language :
; this is the main procedure
(define (palindrome? s)
; it uses `loop` as a helper
(loop <???> <???> <???>))
; loop receives as parameters:
; `s` : the string
; `i` : the current index, starting at 0
; `n` : the string's length
(define (loop s i n)
(cond (<???> ; if `i` equals `n`
<???>) ; then `s` is a palindrome
(<???> ; if the char at the current index != its opposite (*)
<???>) ; then `s` is NOT a palindrome
(else ; otherwise
(loop <???> <???> <???>)))) ; advance the recursion over `i`
Of course, the interesting part is the one marked with (*). Think of it, a string is a palindrome if the char at the 0 index equals the char at the n-1 index (n being the string's length) and the char at the 1 index equals the char at the n-2 index, and so on. In general, if it's true that the char at the i index equals the char at the n-i-1 index (its "opposite") for all i, then we can conclude that the string is a palindrome - but if a single pair of opposite chars is not equal to each other, then it's not a palindrome.
As a further optimization, notice that you don't need to traverse the whole string, it's enough to test the characters up to the half of the string's length (this is explained in Chris' answer) - intuitively, you can see that if the char at i equals the char at n-i-1, then it follows that the char at n-i-1 equals the char at i, so there's no need to perform the same test two times.
Try to write the procedures on your own, and don't forget to test them:
(palindrome? "")
=> #t
(palindrome? "x")
=> #t
(palindrome? "axa")
=> #t
(palindrome? "axxa")
=> #t
(palindrome? "axc")
=> #f
(palindrome? "axca")
=> #f
(palindrome? "acxa")
=> #f
(palindrome? "axcta")
=> #f
Here is a creative answer
(define (palindrome list)
(let halving ((last list) (fast list) (half '()))
(cond ((null? fast) (equal? half last))
((null? (cdr fast)) (equal? half (cdr last)))
(else (halving (cdr last) (cddr fast)
(cons (car last) half))))))
It travels halfway down the list (using fast to find the end), builds up a list of the first half and then simply uses equal? on half with the remainder of list.
Simple.
For each i, from 0 to floor(length / 2), compare the character at index i and at index length - i - 1.
If mismatch, return false.
Otherwise, if the loop runs out, return true.
Skeletal code:
(define (palindrome? str)
(define len (string-length str))
(define halfway <???>)
(let loop ((i 0))
(cond ((>= i halfway) #t)
((char=? <???> <???>)
(loop (+ i 1)))
(else #f))))

Resources