F# match char values
I'm trying to match an integer expre开发者_JS百科ssion against character literals, and the compiler complains about type mismatch.
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 has to be an int because that's what stream.Read returns in order to use -1 as end of file marker. If I replace '!'
with int '!'
it still doesn't work. What's the best way to do this?
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
better style:
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)
The F# language does not have implicit conversation between types as they break compositional (i.e. if you move an operation it changes it's mean as there will no longer be an implicit conversion). You can use the char
operator to change the int returned by the stream to a 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()
精彩评论