Skip to content

Commit

Permalink
StringRepeat[]
Browse files Browse the repository at this point in the history
  • Loading branch information
poke1024 committed Aug 25, 2016
1 parent 9895a6c commit e3c721a
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions mathics/builtin/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,49 @@ def do_subs(py_stri):
return String(do_subs(py_strings))


class StringRepeat(Builtin):
"""
<dl>
<dt>'StringRepeat["$string$", $n$]'
<dd>gives $string$ repeated $n$ times.
<dt>'StringRepeat["$string$", $n$, $max$]'
<dd>gives $string$ repeated $n$ times, but not more than $max$ characters.
</dl>
>> StringRepeat["abc", 3]
= "abcabcabc"
>> StringRepeat["abc", 10, 7]
= abcabcabca
"""

messages = {
'intp': 'A positive integer is expected at position `1` in `2`.',
}

def apply(self, s, n, evaluation):
'StringRepeat[s_String, n_]'
py_n = n.get_int_value() if isinstance(n, Integer) else 0
if py_n < 1:
evaluation.message('StringRepeat', 'intp', 2, Expression('StringRepeat', s, n))
return String(s.get_string_value() * py_n)

def apply_truncated(self, s, n, m, evaluation):
'StringRepeat[s_String, n_Integer, m_Integer]'
py_n = n.get_int_value() if isinstance(n, Integer) else 0
py_m = m.get_int_value() if isinstance(m, Integer) else 0

if py_n < 1:
evaluation.message('StringRepeat', 'intp', 2, Expression('StringRepeat', s, n, m))
if py_m < 1:
evaluation.message('StringRepeat', 'intp', 3, Expression('StringRepeat', s, n, m))

py_s = s.get_string_value()
py_n = min(1 + py_m // len(py_s), py_n)

return String((py_s * py_n)[:py_m])


class Characters(Builtin):
"""
<dl>
Expand Down

0 comments on commit e3c721a

Please sign in to comment.