F#匹配字符值

F#匹配字符值,f#,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 | '!' ->

我试图将整数表达式与字符文本匹配,编译器抱怨类型不匹配

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返回的是int,以便使用-1作为文件结束标记。如果我替换
“!”带有
int'!'它仍然不起作用。最好的方法是什么

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)
更好的风格:

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)
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()
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()

这当然会拾取字符值,但它如何处理文件结尾标记的-1?@首先获取值,然后进行类型转换。这当然会拾取字符值,但它如何处理文件结尾标记的-1?@首先获取值,然后进行类型转换