on master help sign in
Add the toList and fromList functions
commit519484d85a259b0d4b5a3fe8d68f50862232e747 authorEvan Czaplicki <info@elm-lang.org> dateTue 22 Oct 2013, 10:09 (13 years ago) parent463873b
2 files changed+35−8
libraries/Native/String.js+11−4 libraries/String.elm+24−4
libraries/Native/String.js+11−4
@@ -157,8 +157,7 @@ Elm.Native.String.make = function(elm) {
157157 return JS.toList(is);
158158 }
159159
160− function toInt(str) {
161− var s = JS.fromString(str);
160+ function toInt(s) {
162161 var len = s.length;
163162 if (len === 0) { return Maybe.Nothing; }
164163 var start = 0;
@@ -172,8 +171,7 @@ Elm.Native.String.make = function(elm) {
172171 return Maybe.Just(parseInt(s, 10));
173172 }
174173
175− function toFloat(str) {
176− var s = JS.fromString(str);
174+ function toFloat(s) {
177175 var len = s.length;
178176 if (len === 0) { return Maybe.Nothing; }
179177 var start = 0;
@@ -193,6 +191,13 @@ Elm.Native.String.make = function(elm) {
193191 return Maybe.Just(parseFloat(s));
194192 }
195193
194+ function toList(str) {
195+ return JS.toList(str.split('').map(Utils.chr));
196+ }
197+ function fromList(chars) {
198+ return JS.fromList(chars).join('');
199+ }
200+
196201 return Elm.Native.String.values = {
197202 isEmpty: isEmpty,
198203 cons: F2(cons),
@@ -240,5 +245,7 @@ Elm.Native.String.make = function(elm) {
240245
241246 toInt: toInt,
242247 toFloat: toFloat,
248+ toList: toList,
249+ fromList: fromList,
243250 };
244251};
libraries/String.elm+24−4
@@ -14,8 +14,8 @@ are enclosed in `"double quotes"`. Strings are *not* lists of characters.
1414# Check for Substrings
1515@docs contains, startsWith, endsWith, indexes, indices
1616
17−# Conversion To Numbers
18−@docs toInt, toFloat
17+# Conversions
18+@docs toInt, toFloat, toList, fromList
1919
2020# Formatting
2121Cosmetic operations such as padding with extra characters or trimming whitespace.
@@ -85,12 +85,16 @@ filter = Native.String.filter
8585reverse : String -> String
8686reverse = Native.String.reverse
8787
88−{-|
88+{-| Reduce a string from the left:
89+
90+ foldl cons "" "time" == "emit"
8991-}
9092foldl : (Char -> b -> b) -> b -> String -> b
9193foldl = Native.String.foldl
9294
93−{-|
95+{-| Reduce a string from the right:
96+
97+ foldr cons "" "time" == "time"
9498-}
9599foldr : (Char -> b -> b) -> b -> String -> b
96100foldr = Native.String.foldr
@@ -289,3 +293,19 @@ toInt = Native.String.toInt
289293-}
290294toFloat : String -> Maybe Float
291295toFloat = Native.String.toFloat
296+
297+{-| Convert a string to a list of characters.
298+
299+ toList "abc" == ['a','b','c']
300+-}
301+toList : String -> [Char]
302+toList = Native.String.toList
303+
304+{-| Convert a list of characters into a String. Can be useful if you
305+want to create a string primarly by consing, perhaps for decoding
306+something.
307+
308+ fromList ['a','b','c'] == "abc"
309+-}
310+fromList : String -> [Char]
311+fromList = Native.String.fromList