Determine if a string has all the same characters: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) →{{header|Perl 6}}: Simplify, avoid using grammar engine unnecessarily |
→{{header|Python}}: Added a functional draft in Python |
||
Line 268:
"ǞǞǞ" (length: 3), has the same character in all positions.</pre>
=={{header|Python}}==
===Functional===
<lang python>'''Determine if a string has all the same characters'''
from itertools import groupby
# firstDifferingCharLR :: String -> Either String Char
def firstDifferingCharLR(s):
'''Either the first character (if any) that differs from
the character at the head of string, or a message
reporting that no character changes were seen.
'''
groups = list(groupby(s))
return Right(repr(groups[1][0])) if 1 < len(groups) else (
Left('No character changes')
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test of 7 strings'''
for lr in [firstDifferingCharLR(s) for s in [
'',
' ',
'2',
'333',
'.55',
'tttTTT',
'4444 444'
]]:
print(either(lambda l: l)(lambda r: r)(lr))
# GENERIC -------------------------------------------------
# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.
'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
# Left :: a -> Either a b
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.
'''
return {'type': 'Either', 'Right': None, 'Left': x}
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
# MAIN ---
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>No character changes
No character changes
No character changes
No character changes
'5'
'T'
' '</pre>
=={{header|REXX}}==
|