smlnj - SML splitting string on first space -
as of right reading in entire input file using inputall , using string.tokens split each word @ every occurrence of space.
val file = textio.openin input val _input = textio.inputall file val _ = textio.closein file string.tokens char.isspace _input ex) "red blue green" this
["red", "blue", "green"] however, change split string @ first occurrence of space char on each line.
ex) "red blue green" should like
["red", "blue green"] i have feeling need utilize other inputall accomplish this, , main question how make splits @ first space of each line.
textio.inputall fine. in case seems string.tokens not right tool job. write own function, using string.explode , string.implode convert string to/from char list.
fun splitcharsfirstspace cs = case cs of [] => ([], []) | c :: cs' => if char.isspace c ([], cs') else let val (l, r) = splitcharsfirstspace cs' in (c :: l, r) end fun splitfirstspace s = let val (l, r) = splitcharsfirstspace (string.explode s) in (string.implode l, string.implode r) end in context, use follows.
val file = textio.openin input val contents = textio.inputall file val _ = textio.closein file val lines = string.tokens (fn c => c = #"\n") contents val lines' = list.map splitfirstspace lines for example, if input file this:
red blue green yellow orange purple pink then lines' this:
[("red", "blue green"), ("yellow", "orange purple pink")]
Comments
Post a Comment