2010-05-28 54 views
1

我想匹配字符文字的整數表達式,編譯器抱怨類型不匹配。F#匹配字符值

let rec read file includepath = 
    let ch = ref 0 
    let token = ref 0 
    use stream = File.OpenText file 

    let readch() = 
     ch := stream.Read() 
    let lex() = 
     match !ch with 
     | '!' -> 
      readch() 
     | _ -> token := !ch 

ch必須是int,因爲那是stream.Read返回以便使用-1作爲文件標記的結尾。如果我用int '!'替換'!',它仍然不起作用。什麼是最好的方法來做到這一點?

回答

4
open System.IO 
let rec read file includepath = 
    let ch = ref '0' 
    let token = ref '0' 
    use stream = File.OpenText file 

    let readch() = 
     let val = stream.Read(); 
     if val = -1 then xxx 
     else 
      ch := (char)(val) 
      xxx 
    let lex() = 
     match !ch with 
     | '!' -> 
      readch() 
     | _ -> token := !ch 


    0 

更好的風格:

let rec read file includepath = 
    use stream = File.OpenText file 

    let getch() = 
     let ch = stream.Read() 
     if ch = -1 then None 
     else Some(char ch) 

    let rec getToken() = 
     match getch() with 
      | Some ch -> 
       if ch = '!' then getToken() 
       else ch 
      | None -> 
       failwith "no more chars" //(use your own excepiton) 
+0

拾取的字符值,當然,但它是如何處理-1文件標誌的結束? – rwallace 2010-05-28 10:56:30

+0

@just首先獲取值,然後是類型轉換 – 2010-05-28 10:59:35

4

的F#語言沒有類型之間的隱式的對話,因爲他們打破成分(也就是說,如果你將它改變它的平均,因爲將不再是一個隱含的操作轉換)。您可以使用char操作來改變從流返回爲char整型:

open System.IO 
let rec read file includepath = 
    let ch = ref 0 
    let token = ref 0 
    use stream = File.OpenText file 

    let readch() = 
     ch := stream.Read() 
    let lex() = 
     match char !ch with 
     | '!' -> 
      readch() 
     | _ -> token := !ch 
    lex()