2010-05-28 51 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()