简体   繁体   中英

Creating instance of State in Frege

In y-taka-23 adaptation of LYAH I found that most of snippets for Chapter 13 must deal with lack of State constructor, for example original Haskell code:

randomSt = State random 

is rewritten as:

randomSt = do
    gen <- State.get
    let (x, newGen) = random gen
    State.put newGen
    return x 

This of course has its own didactic merits! But I wonder if there is another way of creating instance of State . I know that this discrepancy between Frege and Haskell comes from the fact that State sa in Frege's Control.monad.State module is an abstract data type. Is it possible to define new concrete data type which derives from it and use its constructor instead?

Can't you just write a smart constructor?

state :: (s -> (a, s)) -> State s a
state f = do
    s <- State.get
    let (x, s') = f s
    State.put s'
    return x

Write it once (maybe in a library you make available for download?) and then use it anywhere you need it.

Indeed, the construction of some specific state instance with

State random

is quite elegant, and it's impossible in Frege because the State data constructor is not accessible. This is unfortunate, but it also protects you from writing code that depends on some implementation details.

For example, I'm currectly working on a new backend for Frege that utilizes Java lambdas and tries to emit typesafe generic Java code, and in the course of doing this it turned out that I need another representation for State. Thus, in the next Frege release, there simply is no State constructor anymore that would take a function as argument.

Despite of this change and the fact that big parts of the compiler consist of State operations, I didn't had to change any single line in the compiler code because of this. And I can alos be sure hat I won't hurt anybody else's code. Big win!

Anyway, I feel like we could include @jcast's smart state constructor in the standard library. (I'd just rewrite the let into a case.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM