I have a project in Common Lisp and I need help.
I have for example the list:
(( C ) ( A C ) ( ) ( ) ( P B ) ( ) ( C C A ) ( A ))
and I want to replace all the sublists except the sublist which contains the element P. There's only one P in the whole list and it's always the first element in a sublist. So the result should be:
(NIL NIL NIL NIL ( P B ) NIL NIL NIL)
Your problem combines mapping and membership testing. Both of these functionalities are available in common lisp:
(mapcar (lambda (list) (member 'p list))
'((c) (a c) () () (p b) (c c a) (a)))
;; (NIL NIL NIL NIL (P B) NIL NIL)
More documentation on mapping can be found in the hyperspec
We could also use iteration:
(loop for item in '((c) (a c) () () (p b) (c c a) (a))
collect (member 'p item))
;; (NIL NIL NIL NIL (P B) NIL NIL)
Related
I'm trying to write a function called: get-element (board coords) that takes a board and a pair of coords representing a board position as input. The first element of the pair represents the column number and the second represents the row number (indexing starts from 0). The function returns the contents of that board position, which can be either X, O or NIL. Using the following test board state.
(defparameter *test-board*
'((nil nil nil nil nil nil)
(O nil nil nil nil nil)
(X nil nil nil nil nil)
(X X O nil nil nil)
(O O X nil nil nil)
(nil nil nil nil nil nil)
(nil nil nil nil nil nil)))
The function should work like so:
(get-element *test-board* ‘(0 0))
> NIL
I can't seem to understand the process to gain such as output. So far my code is as follows (But this is seriously wrong!):
(col(nth 0 coords))
(row(nth 1 coords)))
Any help with understanding how to retrieve specific elements within a list would be much appreciated!
I will not give you the exact solution, but a reasoning that I hope will be useful to produce it by yourself.
Your data structure consists of a list, each element of which represent a row of the board. So you have a list with a number of elements equal to the number of rows of the board.
The elements of such list are themselves lists: so each row is represented by a list, in which each element represents a particular cell of the board (not a column, a cell!). So, your data structure is a list of lists.
So, one could ask: what is a column of the board in this representation? And the answer is: there is no actual data structure that can be called the column of the board, simply a column can be abastractly seen as: "all the elements at the same position of the internal lists".
So, if you want to extract a particular cell from your board representation, identified by a couple of coordinates (row number, column number), you must “translate” this information to your specific representation of the data structure, which is expressed instead in list of lists. For instance, if you want to get the content of the cell at the coordinates (3, 5), that is row 3 and column 5, you should reason in this way: I can access directly to the row 3, since it is the fourth element of the “big” list, but not to the column 5, since there is nothing immediately corresponding ot it.
But if I can access to row 3, for instance with (nth 3 board), what I obtain is the list corresponding to the cells of such row, so there is no need to get column 5, I can just take element 5 of this list and I will get the content of the cell with coordinate (3, 5). So, it is sufficient to get the element number 5 of this list, for instance with (nth 5 (nth 3 board)) (that is, since (nth 3 board) returns the list of cells of that row, you select the element 5 from that list).
I hope this can be useful to understand how to solve your problem.
(defun get-element (list-of-list coord)
"Return value of field in list-of-list."
(let ((row (nth (first coord) list-of-list)))
(nth (second coord) row)))
(defparameter *test-board*
'((nil nil nil nil nil nil)
(O nil nil nil nil nil)
(X nil nil nil nil nil)
(X X O nil nil nil)
(O O X nil nil nil)
(nil nil nil nil nil nil)
(nil nil nil nil nil nil)))
(get-element *test-board* '(0 0)) ;; NIL
(get-element *test-board* '(1 0)) ;; O
(get-element *test-board* '(4 2)) ;; X
This function will numerically select from a nested list, to any depth:
(defun nested-list-coord-select (nested-list coords)
(loop for coord in coords
with current = nested-list
do (setf current (nth coord current))
finally (return current)))
[1]> (nested-list-coord-select '((a a)) '(0 0))
A
[2]> (nested-list-coord-select '((a a)) '(0 1))
A
[3]> (nested-list-coord-select '((a b)) '(0 1))
B
[4]> (nested-list-coord-select '((a b (c d))) '(0 1))
B
[5]> (nested-list-coord-select '((a b (c d))) '(0 2))
(C D)
[6]> (nested-list-coord-select '((a b (c d))) '(0 2 0))
C
[7]> (nested-list-coord-select '((a b (c d))) '(0 2 1))
D
[8]> (nested-list-coord-select '((a b (c d))) '(0 2 1 3))
*** - NTH: D is not a list
[9]> (nested-list-coord-select nil nil)
NIL
[10]> (nested-list-coord-select 42 nil)
42
If we replace nth using elt (remembering to reverse the arguments), then it becomes more generic. We can have a vector of lists of strings, and such.
Remark: ANSI Common Lisp has N-dimensional arrays, you know.
I want to implement an instance of Applicative for my custom list.
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Eq a => EqProp (List a) where (=-=) = eq
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons a Nil) = (Cons (f a) Nil)
fmap f (Cons a as) = (Cons (f a) (fmap f as))
main = do
let trigger = undefined :: List (Int, String, Int)
quickBatch $ applicative trigger
instance Arbitrary a => Arbitrary (List a) where
arbitrary = sized go
where go 0 = pure Nil
go n = do
xs <- go (n - 1)
x <- arbitrary
return (Cons x xs)
instance Applicative List where
pure x = (Cons x Nil)
Nil <*> _ = Nil
_ <*> Nil = Nil
(Cons f fs) <*> (Cons a as) = (Cons (f a) (fs <*> as))
This gives the following bugs:
λ> main
applicative:
identity: *** Failed! Falsifiable (after 3 tests):
Cons 0 (Cons (-1) Nil)
composition: *** Failed! Falsifiable (after 3 tests):
Cons <function> (Cons <function> Nil)
Cons <function> (Cons <function> Nil)
Cons 1 (Cons (-2) Nil)
homomorphism: +++ OK, passed 500 tests.
interchange: +++ OK, passed 500 tests.
functor: *** Failed! Falsifiable (after 3 tests):
<function>
Cons (-2) (Cons (-1) Nil)
First is the id law is failing:
λ> Cons id Nil <*> Cons 0 (Cons (-1) Nil)
Cons 0 Nil
How do I fix this? pure takes an a not a List a so I do not see how to match on List and preserve the nested list structure.
The composition law also fails which is not strange:
λ> (Cons "b" Nil) <*> (Cons "c" Nil)
<interactive>:295:7:
Couldn't match expected type ‘[Char] -> b’
with actual type ‘[Char]’
Relevant bindings include
it :: List b (bound at <interactive>:295:1)
In the first argument of ‘Cons’, namely ‘"b"’
In the first argument of ‘(<*>)’, namely ‘(Cons "b" Nil)’
In the expression: (Cons "b" Nil) <*> (Cons "c" Nil)
Edit: since I got great answers implementing applicative for ziplists, I have changed the question to be about ziplists.
For your ZipList-like approach we expect the following left-identity to hold:
pure id <*> someList = someList
For this, pure cannot return a single-element list, since this will stop immediately:
(Cons id Nil) <*> Cons 1 (Cons 2 Nil)
= Cons (id 1) (Nil <*> Cons 2 Nil)
= Cons 1 Nil
Which isn't the expected result for the left-identity. If pure cannot return only a single element list, how many should it return? The answer is: infinite:
repeatList :: a -> List a
repeatList x = let c = Cons x c in c
Why did I call this the ZipList approach? Because it's the same behaviour as in Control.Applicative.ZipList, which can be motivated with zipWith:
zipWithList :: (a -> b -> c) -> List a -> List b -> List c
zipWithList f (Cons x xs) (Cons y ys) = Cons (f x y) (zipWithList f xs ys)
zipWithList _ _ _ = Nil
Now your instance is
instance Applicative List where
pure = repeatList
(<*>) = zipWithList ($)
However, checkers cannot check this instance either due to your EqProb instance, since pure f <*> pure x == pure (f x) (homomorphism) results in a check on infinite lists. You can provide an alternative one, though. For example, you can take an arbitrary number of elements and compare them:
prop_sameList :: Eq a => (Int, Int) -> List a -> List a -> Property
prop_sameList bounds xs ys = forAll (choose bounds) $ \n ->
takeList n xs `eq` takeList n ys
takeList :: Int -> List a -> List a
takeList _ Nil = Nil
takeList n (Cons x xs)
| n <= 0 = Nil
| otherwise = Cons x (takeList (n - 1) xs)
Then, if you want to compare at least 1000 and at most 10000 elements, you can use:
instance Eq a => EqProb (List a) where
(=-=) = prop_sameList (1000, 10000)
After all, we're just trying to find a list where our property does not hold.
Expanding on my comment to Zeta's much more deserving answer, you need a second change to get this test to run:
-- | Test lists for equality (fallibly) by comparing finite prefixes
-- of them. I've arbitrarily chosen a depth of 1,000. There may be
-- better ideas than that.
instance Eq a => EqProp (List a) where
xs =-= ys = takeList 1000 xs `eq` takeList 1000 ys
-- | Take a prefix of up to #n# elements from a 'List'.
takeList :: Int -> List a -> List a
takeList _ Nil = Nil
takeList n (Cons a as)
| n > 0 = Cons a (takeList (n-1) as)
| otherwise = Nil
With Zeta's changes and this one, your test suite passes:
applicative:
identity: +++ OK, passed 500 tests.
composition: +++ OK, passed 500 tests.
homomorphism: +++ OK, passed 500 tests.
interchange: +++ OK, passed 500 tests.
functor: +++ OK, passed 500 tests.
The key insight to get here is that QuickCheck is, fundamentally, a tool for finding counterexamples to properties. QuickCheck generally cannot prove that a property holds for all possible inputs, because the domain may be infinite. That's the reason why there's an EqProp class in checkers ("Types of values that can be tested for equality, perhaps through random sampling")—so that we may implement techniques for searching for counterexamples for types and tests that don't admit of simple equality comparisons.
I am using Glasgow Haskell Compiler, Version 7.8.3, stage 2 booted by GHC version 7.6.3.
I attempted to use the following data definition for a List type in Haskell:
data Eq a => List a = Nil | Cons a (List a)
However, the -XDatatypeContexts flag is required, depricated, and even removed from the language by default. It is widely viewed as a misfeature of the language. I also do not want to have to use special flags for my definition of List since I am trying to replicate the functionality of the existing list type.
Then I was able to use the following segment of code instead:
data List a where
Nil :: List a
Cons :: Eq a => a -> List a -> List a
It runs fine. The visible issue with this solution is that now I need to use the -XGADTs flag, which I still don't want to depend on in this case since it is not necessary for the built in version of list to function. Is there a way to restrict the type within Cons to be Eq a so that I can compare two lists without the need for compiler flags and without using the derived keyword?
The remaining code is as follows:
instance Eq (List a) where
(Cons a b) == (Cons c d) = (a == c) && (b == d)
Nil == Nil = True
_ == _ = False
testfunction = Nil :: List Int
main = print (if testfunction == Nil then "printed" else "not printed")
I see that the following solution works:
data List a = Nil | Cons a (List a)
instance Eq a => Eq (List a) where
(Cons a b) == (Cons c d) = (a == c) && (b == d)
Nil == Nil = True
_ == _ = False
testfunction = Nil :: List Int
main = print (if testfunction == Nil then "printed" else "not printed")
However, for some reason, it does not work with a manual definition for Eq (Equals here).
class Equal a where
(=+=) :: a -> a -> Bool
(/+=) :: a -> a -> Bool
x =+= y = not (x /+= y)
x /+= y = not (x =+= y)
data List a = Nil | Cons a (List a)
instance Equal a => Equal (List a) where
(Cons a b) =+= (Cons c d) = (a =+= c) && (b =+= d)
Nil =+= Nil = True
_ =+= _ = False
testfunction = Nil :: List Int
main = print (if testfunction =+= Nil then "printed" else "not printed")
I get the following error:
No instance for (Equal Int) arising from a use of ‘=+=’
In the expression: testfunction =+= Nil
In the first argument of ‘print’, namely
‘(if testfunction =+= Nil then "printed" else "not printed")’
In the expression:
print (if testfunction =+= Nil then "printed" else "not printed")
However, by using GADT's, I can show that my Equal class does actually function. This code works:
class Equal a where
(=+=) :: a -> a -> Bool
(/+=) :: a -> a -> Bool
x =+= y = not (x /+= y)
x /+= y = not (x =+= y)
data List a where
Nil :: List a
Cons :: Equal a => a -> List a -> List a
instance Equal (List a) where
(Cons a b) =+= (Cons c d) = (a =+= c) && (b =+= d)
Nil =+= Nil = True
_ =+= _ = False
testfunction = Nil :: List Int
main = print (if testfunction =+= Nil then "printed" else "not printed")
However, I have to use instance Equal (List a) where instead of instance Equal a => Equal (List a) where otherwise I get the error:
No instance for (Equal Int) arising from a use of ‘=+=’
In the expression: testfunction =+= Nil
In the first argument of ‘print’, namely
‘(if testfunction =+= Nil then "printed" else "not printed")’
In the expression:
print (if testfunction =+= Nil then "printed" else "not printed")
It looks like you're trying to restrict lists to only be able to hold values that implement Eq, and you can't do that without extensions. You can, however, tell the compiler how to compare two List as when a has a type that implements Eq. There are two easy ways to do this. The simplest is with a deriving statement:
data List a = Nil | Cons a (List a) deriving (Eq)
Or you can define it manually:
instance Eq a => Eq (List a) where
(Cons a b) == (Const c d) = (a == c) && (b == d)
Nil == Nil = True
_ == _ = False
Now whenever you fill your List type with something that implements Eq, the list will also be comparable using ==. There's no need to restrict the values that can be inside Cons. You can certainly have a normal list of functions, like
fs1 :: [Int -> Int]
fs1 = [(+1), (*3), (+2), (*4)]
Or in your case
fs2 :: List (Int -> Int)
fs2 = Cons (+1) $ Cons (*3) $ Cons (+2) $ Cons (*4) Nil
Which can be used as
> map ($ 10) fs1
[11, 30, 12, 40]
And given
map' :: (a -> b) -> List a -> List b
map' f Nil = Nil
map' f (Cons x xs) = Cons (f x) (map' f xs)
Then
> map' ($ 10) fs2
Cons 11 (Cons 30 (Cons 12 (Cons 40 Nil)))
Although to actually view it in GHCi you should also derive Show:
data List a = Nil | Cons a (List a) deriving (Eq, Show)
There are several other useful typeclasses that can be derived in GHC, too.
To make it work with your custom Equal typeclass, you'll have to write multiple instances by hand:
class Equal a where
(=+=) :: a -> a -> Bool
(/+=) :: a -> a -> Bool
x =+= y = not (x /+= y)
x /+= y = not (x =+= y)
instance Equal Int where
x =+= y = x == y
instance Equal a => Equal (List a) where
(Cons a b) =+= (Cons c d) = (a =+= c) && (b =+= d)
Nil =+= Nil = True
_ =+= _ = False
Now because you have an instance Equal Int and Equal a => Equal (List a), you can compare two List Ints:
> let x = Cons 1 (Cons 2 (Cons 3 Nil)) :: List Int
> let y = Cons 1 (Cons 2 (Cons 3 Nil)) :: List Int
> x =+= y
True
> x =+= Nil
False
For whatever type you want to store in a List and use =+= on, you'll have to implement Equal for that type.
The usual solution to this is to to use this structure:
data List a = Nil | Cons a (List a)
instance Eq a => Eq (List a) where
(Cons a b) == (Cons c d) = (a == c) && (b == d)
Nil == Nil = True
_ == _ = False
Noticed I've added Eq a as a constraint to the instance, not to the data type. This way all the lists that you could compare for equality the way you're trying to write it can be compared for equality, but you also allow the existence of lists of things which cannot be compared for equality. And this is supported by every version of Haskell you will encounter, even very old ones, with no extensions.
This approach then also extends nicely when you want to add a Show instance, an Ord instance, etc; to do it your way you have to keep going back and making the data structure more restrictive by adding more constraints (potentially breaking existing code that worked fine because it didn't need those instances). Whereas if you leave the data type unconstrained and just make your instances Show a => Show (List a), Ord a => Ord (List a), etc, then you can show and order lists of types which happen to support both, but you can still have (and show) lists of types that support Show but not Ord and vice versa.
Plus, there are lots of useful type classes for parameterised types (such as List a) that require them to be fully generic in their type parameter. Examples are Functor, Applicative, Monad; it is not possible to correctly implement these for the constrained list type you're trying to create.
While it is possible to create constrained lists like you're trying to (but only by using extensions, as you've found), it has been found to be usually much more useful to leave your data types fully generic in their type parameter, and if a particular usage of your type needs to impose restrictions on the type parameter you impose them at that usage site, not at every use of the data type. This should be your "default setting"; depart from it when you have a good reason (you may well have such a reason here, but you haven't given it to us in the question, so nobody can recommend the best way of handling it).
how do i convert an input to a list?
(define (conjuger v t p)
(cond ((equal? t '(present)) (present (radical v) p))
I want to input the V as a word, but i am forced to type it as a list for the program to work. Is there a way to have scheme do this:
'(m a n g e r) => '(manger)
'(manger) => '(m a n g e r)
Try this for the first part:
(define (implode lst)
(string->symbol
(apply string-append
(map symbol->string lst))))
(list (implode '(m a n g e r)))
; => '(manger)
And this for the second part:
(define (explode itm)
(map (lambda (c) (string->symbol (string c)))
(string->list
(symbol->string itm))))
(explode (car '(manger)))
; => '(m a n g e r)
Notice that in your code you're using symbols, not strings. I wrote my answer accordingly.
This is the version of Nils M. Holm, Sketchy Scheme. 4.5th edition (Raleigh 2011) p. 72–74:
(define (compose f g)
(lambda x
(f (apply g x))))
(define symbol->list
(compose string->list symbol->string))
(define (explode item)
(map (lambda (item)
(string->symbol
(string item)))
(symbol->list item)))
(define (implode item)
(letrec
((sym->char
(lambda (item)
(let ((string (symbol->string item)))
(if (not (= (string-length string) 1))
(error "bad symbol -- IMPLODE")
(string-ref string 0))))))
(string->symbol
(list->string
(map sym->char item)))))
scheme#(guile-user)> (explode 'foo)
$1 = (f o o)
scheme#(guile-user)> (implode '(b a r))
$2 = bar
Older versions of the book are avaible online for free in pdf or html format under the title »sketchy lisp« (dealing explicitly with Scheme, though). The problem of splitting symbols into lists and vice versa is treated in chapter 2.5.
In Python there are functions all and any they return true if all or some elements of a list are true respectively. Are there equivalent functions in Common Lisp? If not, what is the most succinct and idiomatic way to write them?
Currently i have this:
(defun all (xs)
(reduce (lambda (x y) (and x y)) xs :initial-value t))
(defun any (xs)
(reduce (lambda (x y) (or x y)) xs :initial-value nil))
In Common Lisp, use every (that's the equivalent of all) and some (that's the equivalent of any).
You can use the LOOP macro with ALWAYS and THEREIS clauses like this:
CL-USER 1 > (loop for item in '(nil nil nil) always item)
NIL
CL-USER 2 > (loop for item in '(nil nil t) always item)
NIL
CL-USER 3 > (loop for item in '(t t t) always item)
T
CL-USER 4 > (loop for item in '(nil nil nil) thereis item)
NIL
CL-USER 5 > (loop for item in '(nil nil t) thereis item)
T
CL-USER 6 > (loop for item in '(t t t) thereis item)
T