Skip to content

Commit

Permalink
String functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
corywalker committed Aug 1, 2017
1 parent 6f36dfd commit 3fc1e48
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 2 deletions.
43 changes: 43 additions & 0 deletions expreduce/builtin_string.go
Expand Up @@ -44,5 +44,48 @@ func GetStringDefinitions() (defs []Definition) {
Name: "Infix",
toString: (*Expression).ToStringInfix,
})
defs = append(defs, Definition{
Name: "StringLength",
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
if len(this.Parts) != 2 {
return this
}
asStr, isStr := this.Parts[1].(*String)
if !isStr {
return this
}
return NewInt(int64(len(asStr.Val)))
},
})
defs = append(defs, Definition{
Name: "StringTake",
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
if len(this.Parts) != 3 {
return this
}
asStr, isStr := this.Parts[1].(*String)
if !isStr {
return this
}
asList, isList := HeadAssertion(this.Parts[2], "System`List")
if !isList || len(asList.Parts) != 3 {
return this
}
sInt, sIsInt := asList.Parts[1].(*Integer)
eInt, eIsInt := asList.Parts[2].(*Integer)
if !sIsInt || !eIsInt {
return this
}
s := int(sInt.Val.Int64()-1)
e := int(eInt.Val.Int64()-1)
if s < 0 || e >= len(asStr.Val) {
return this
}
if e < s {
return &String{""}
}
return &String{asStr.Val[s:e+1]}
},
})
return
}
4 changes: 2 additions & 2 deletions expreduce/resources.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions expreduce/resources/string.m
Expand Up @@ -37,3 +37,23 @@
ESameTest["(bar|fuzz|zip)", Infix[foo[Global`bar, Global`fuzz, Global`zip], "|"] // ToString]
]
};

StringLength::usage = "`StringLength[s]` returns the length of s.";
Attributes[StringLength] = {Listable, Protected};
Tests`StringLength = {
ESimpleExamples[
ESameTest[5, StringLength["Hello"]]
]
};

StringTake::usage = "`StringTake[s, {start, end}]` takes a substring of s.";
Attributes[StringTake] = {Protected};
Tests`StringTake = {
ESimpleExamples[
ESameTest["h", StringTake["hello", {1, 1}]],
ESameTest[StringTake["hello", {0, 1}], StringTake["hello", {0, 1}]],
ESameTest["hello", StringTake["hello", {1, StringLength["hello"]}]],
ESameTest["", StringTake["hello", {2, 1}]],
ESameTest[StringTake["hello", {2, 999}], StringTake["hello", {2, 999}]]
]
};

0 comments on commit 3fc1e48

Please sign in to comment.