Haskell: let statement, copy data type to itself with/without modification not working

前端 未结 3 424
傲寒
傲寒 2021-01-16 05:35

I want to update a record syntax with a change in one field so i did something like:

let rec = rec{field = 1}

But I\'ve noticed that i can\

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 06:33

    The issue you're running into is that all let and where bindings in Haskell are recursive by default. So when you write

    let rec = rec { ... }
    

    it tries to define a circular data type that will loop forever when you try to evaluate it (just like let a = a).

    There's no real way around this—it's a tradeoff in the language. It makes recursive functions (and even plain values) easier to write with less noise, but also means you can't easily redefine a a bunch of times in terms of itself.

    The only thing you can really do is give your values different names—rec and rec' would be a common way to do this.

    To be fair to Haskell, recursive functions and even recursive values come up quite often. Code like

    fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
    

    can be really nice once you get the hang of it, and not having to explicitly mark this definition as recursive (like you'd have to do in, say, OCaml) is a definite upside.

提交回复
热议问题