Increment value in F#

前端 未结 3 461
故里飘歌
故里飘歌 2021-01-17 13:11

Maybe it\'s too simple thing to do, but I can\'t find any answer in the web
I\'m try to Increment value in F# (like count++ in C#).
I don\'t want to use

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-17 14:03

    If you don't want to use mutable then you can't really do a destructive update like ++ is in C#. You could shadow a variable with a new one with the same name e.g.

    let x = 4;
    let x = x + 1 in (x+4)  //returns 8
    

    although you couldn't write this as a function.

    EDIT: If do want to use mutable variables then you can create a function which modifies a ref:

    let increment (ir: int ref) = ir := !ir + 1
    

    You can then use it as

    let i = ref 1
    increment i
    let iv = !i    //iv contains 2
    

    As Tomas points out in his answer, this function already exists and is called incr.

提交回复
热议问题