Recursive records in F#

前端 未结 2 805
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 08:16

A friend and I are reading up on F# and are messing around with records at the moment.

We have made the following record for representing a person:

t         


        
相关标签:
2条回答
  • 2021-01-13 09:01

    If you declare father and mother as Parent option then you can use it like:

    let f = { name = "Father"; father = None; mother = None }
    let m = { name = "Mother"; father = None; mother = None }
    let c = { name = "Child"; father = Some(f); mother = Some(m) }
    

    without using Parent option for father and mother you would have to create a "null parent" instance and use that instead of None.

    0 讨论(0)
  • 2021-01-13 09:11

    Lee shows a more useful definition, but you can create an instance of your Person type:

    let rec loopy = { name = "loopy"; father = loopy; mother = loopy }
    

    or

    let rec male = { name = "male"; father = male; mother = female }
      and female = { name = "female"; father = male; mother = female}
    

    Of course, these aren't at all helpful if you're modeling real people, but the compiler doesn't know that. A similar recursive type could be useful if you're trying to define a cycle, for instance.

    0 讨论(0)
提交回复
热议问题