Lisp Extraction Mission
Common Lisp, 99
The following 99 bytes solution is a CL version of the nice Scheme answer.
(defun g(l n &optional(o'l))(if(eql n l)o(and(consp l)(or(g(car l)n`(car,o))(g(cdr l)n`(cdr,o))))))
I originally tried to make use of position
and position-if
, but it turned out to be not as compact as I would have liked (209 bytes):
(lambda(L x &aux(p'l))(labels((f(S &aux e)(cons(or(position x S)(position-if(lambda(y)(if(consp y)(setf e(f y))))S)(return-from f()))e)))(dolist(o(print(f L))p)(dotimes(i o)(setf p`(cdr,p)))(setf p`(car,p)))))
Expanded
(lambda
(l x &aux (p 'l))
(labels ((f (s &aux e)
(cons
(or (position x s)
(position-if
(lambda (y)
(if (consp y)
(setf e (f y))))
s)
(return-from f nil))
e)))
(dolist (o (print (f l)) p)
(dotimes (i o) (setf p `(cdr ,p)))
(setf p `(car ,p)))))
Example
(funcall *fun* '(4 5 (1 2 (7) 9 (10 8 14))) 14)
The list is quoted, but if you really want, I can use a macro. The returned value is[1]:
(CAR (CDR (CDR (CAR (CDR (CDR (CDR (CDR (CAR (CDR (CDR L)))))))))))
For tests, I used to generate a lambda form where l
was a variable:
(LAMBDA (#:G854) (CAR (CDR (CDR (CAR (CDR (CDR (CDR (CDR (CAR (CDR (CDR #:G854))))))))))))
Calling this with the original list returns 14.
[1] (caddar (cddddr (caddr l)))
would be nice too
Retina, 170 142 125 115 114 87 84 83 75 73 70 69 68 67 bytes
Yay, less than 50% of more than 100 bytes off my first attempt. :)
\b(.+)\b.* \1$
(
^.
l
\(
a
+`a *\)|\d
d
+`(.*[l)])(\w)
(c$2r $1)
To run the code from a single file, use the -s
flag.
I'm still not convinced this is optimal... I won't have a lot of time over the next few days, I will add an explanation eventually.
Pyth, 62 bytes
JvXz"() ,][")u?qJQG&=J?K}Quu+GHNY<J1)hJtJ++XWK"(cdr "\d\aG\)\l
Try it online: Demonstration or Test Suite
Explanation:
The first bit JvXz"() ,][")
replaces the chars "() "
with the chars "[],"
in the input string, which ends up in a representation of a Python-style list. I evaluate it and store it in J
.
Then I reduce the string G = "l"
with u...\l
. I apply the inner function ...
repeatedly to G
, until the value of G
doesn't change anymore and then print G
.
The inner function does the following: If J
is already equal to the input number, than don't modify G
(?qJQG
). Otherwise I'll flatten the the list J[:1]
and check if the input number is in that list and save this to the variable K
(K}Quu+GHNY<J1)
). Notice that Pyth doesn't have a flatten operator, so this is takes quite a few bytes. If K
is true, than I update J with J[0]
, otherwise with J[1:]
(=J?KhJtJ
). And then I replace G
with "(cdr G)"
and replace the d
the a
, if K
is true (++XWK"(cdr "\d\aG\)
).