Substring/Top and tail: Difference between revisions
Content added Content deleted
(→{{header|Python}}: Variant - composing atomic functional expressions for slices) |
|||
Line 1,343: | Line 1,343: | ||
print "socks"[:-1] # strip last character |
print "socks"[:-1] # strip last character |
||
print "brooms"[1:-1] # strip both first and last characters</lang> |
print "brooms"[1:-1] # strip both first and last characters</lang> |
||
Or, composing atomic functional expressions for these slices: |
|||
<lang python>from functools import (reduce) |
|||
def main(): |
|||
print ( |
|||
ap([tail, init, compose(init)(tail)])( |
|||
["knights"] |
|||
) |
|||
) |
|||
# --> ['nights', 'knight', 'night'] |
|||
# GENERIC ------------------------------------------------- |
|||
# tail :: [a] -> [a] |
|||
def tail(xs): |
|||
return xs[1:] |
|||
# init::[a] - > [a] |
|||
def init(xs): |
|||
return xs[:-1] |
|||
# ap (<*>) :: [(a -> b)] -> [a] -> [b] |
|||
def ap(fs): |
|||
return lambda xs: reduce( |
|||
lambda a, f: a + reduce( |
|||
lambda a, x: a + [f(x)], xs, [] |
|||
), fs, [] |
|||
) |
|||
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c |
|||
def compose(g): |
|||
return lambda f: lambda x: g(f(x)) |
|||
if __name__ == '__main__': |
|||
main()</lang> |
|||
{{Out}} |
|||
<pre>['nights', 'knight', 'night']</pre> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |