F#匹配char值

时间:2010-05-28 10:45:09

标签: 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 '!',它仍然无效。最好的方法是什么?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:4)

F#语言在类型之间没有隐式对话,因为它们打破了组合(即如果你移动一个操作,它会改变它的意思,因为不再有隐式转换)。您可以使用char运算符将流返回的int更改为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()