Skip to content

Instantly share code, notes, and snippets.

@MichaelBlume
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelBlume/17a227cc839f52f68c97 to your computer and use it in GitHub Desktop.
Save MichaelBlume/17a227cc839f52f68c97 to your computer and use it in GitHub Desktop.
Find-in
; http://an-animal-imagined-by-poe.tumblr.com/post/97790330928/i-have-been-busy-distracted-absent-for-the-past
(defn find-in
([needle haystack] (find-in needle haystack 'x))
([needle haystack varname]
; varname remminds us of how we got the haystack we're looking at from x
(or
; base case
(when (= needle haystack)
varname)
; if the haystack is a symbol we're screwed
(when-not (symbol? haystack)
(or
; try looking at the first element of the haystack
(when (seq haystack)
(find-in
needle
(first haystack)
(list 'first varname)))
; or in the rest of it?
(when (seq haystack)
(find-in
needle
(rest haystack)
(list 'rest varname)))
; maybe we can cons together the parts of the needle
; from different parts of the haystack
(when-not (symbol? needle)
(when-let
[car (find-in
(first needle)
haystack
varname)]
(when-let
[cdr (find-in
(rest needle)
haystack
varname)]
(list 'cons car cdr)))))))))
(defn exercise-find-in [needle haystack]
(eval
`(let [~'x (quote ~haystack)]
~(find-in needle haystack))))
@ohAitch
Copy link

ohAitch commented Sep 18, 2014

In rosetta-code interests, slightly unconventional to be more verbatim:

++  conv  $&  [p=conv q=conv]
              [%0 p=@b]
++  find-in
  |=  [needle=noun hay=noun]
  ^-  (unit conv)
  =|  axe=(list ?(%0 %1))                               ::  axis acummulator
  |-
  ?:  =(needle hay)
    [~ u=(rap 0 [1 (flop axe)])]                        ::  (some {axis})
  ?@  hay
    ~                                                   ::  fail if hay is atom
  =+  top=$(hay -.hay, axe [%0 axe])
  ?^  top
    u.top                                               ::  cell is success
  =+  bot=$(hay +.hay, axe [%1 axe])
  ?^  bot
    u.bot
  ?@  needle                                            ::  descend unless atom
    ~
  =+  car=$(needle -.needle)
  ?~  car
    ~                                                   ::  lost head is failure
  =+  cdr=$(needle -.needle)
  ?~  cdr
    ~
  [~ u=[-.car -.cdr]]

@ohAitch
Copy link

ohAitch commented Sep 19, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment