How do I extract the middle element(s) of a given list?
Update #2, after reading the other answers:
mid[a_List] := a[[# ;; -#]] & @ ⌈Length@a/2⌉
mid /@ {{a, b, c}, {a, b, c, d}}
{{b}, {b, c}}
Update: better:
mid[a_List] := Take[a, Quotient[{1.5, 2.5} + Length@a, 2]]
I came up with this:
mid[a_List] := Take[a, Round[{-.1,.1} + (1 + Length@a)/2]]
Hm, no recursion solution yet? Strange... Here we go then:
extract[x_] := x; extract[{_, x__, _}] := extract[{x}]
extract /@ {{a}, {a, b}, {a, b, c}, {a, b, c, d}}
(*{{a}, {a, b}, {b}, {b, c}}*)
middle[li_List] := Part[li, Union@Through[{Floor, Ceiling}[(Length@li + 1)/2]]]
I wouldn't do it this way, but just for fun:
mid[li_List] := With[{len = Length@li}, li[[Nearest[Range[len], (len + 1)/2]]]]