2017-04-08 10 views
0

今のところ、inputAllを使用して入力ファイル全体を読み込み、String.tokensを使用してスペースが発生するたびに各単語を分割しています。最初のスペースにSMLを分割する文字列

val file = TextIO.openIn input 
val _input = TextIO.inputAll file 
val _ = TextIO.closeIn file 
String.tokens Char.isSpace _input 

例)「赤、青、緑は」しかし、今私は、各ライン上のスペース文字の最初の発生時に文字列を分割し、それを変更したいと思い、この

["red", "blue", "green"] 

ようになります。 。

例)「赤青緑」

["red", "blue green"] 

のようになります。私はこれを達成するためにinputAll以外のものを使用する必要があります感じている、と私の主な質問は、あなたがそれようにそれを作るのですかどのようです各行の最初のスペースでのみ分割されます。

答えて

1

TextIO.inputAllです。この場合、String.tokensは仕事のための適切なツールではないようです。個人的には、String.explodeString.implodeを使用してstringを/からchar listに変換するだけで、私自身の関数を書くことになります。

fun splitCharsFirstSpace cs = 
    case cs of 
    [] => ([], []) 
    | c :: cs' => 
     if Char.isSpace c then ([], 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 

コンテキストでは、次のように使用できます。例えば

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 

、入力ファイルは、このだった場合:

red blue green 
yellow orange purple pink 

そしてlines'は次のようになります。ここでは

[("red", "blue green"), ("yellow", "orange purple pink")] 
1

は、関数のdroplを使用して別のオプション、droprで、 Substring のsplitlとTextIO.inputLineのsplitl。

structure SS = Substring; 
    structure C = Char; 
    structure TIO = TextIO; 

    fun splitFile(arg) = 
    let val file = TIO.openIn arg 
     val line = TIO.inputLine file; 
     fun trimWs ss = (SS.dropl (C.isSpace) (SS.dropr (C.isSpace) ss)); 
     fun splitLine(SOME str) acc = 
     let val (l, r) = SS.splitl (not o C.isSpace) (SS.full str); 
      val (l, r) = (trimWs l, trimWs r); 
     in if SS.size l + SS.size r = 0 
       then splitLine (TIO.inputLine file) acc 
       else (SS.string l, SS.string r)::splitLine (TIO.inputLine file) acc 
     end 
     | splitLine (NONE) acc = acc; 
     val result = splitLine line []; 
     val _ = TextIO.closeIn file 
    in result end 
関連する問題