简体   繁体   English

Haskell无限类型

[英]Haskell Infinite Type

I'm trying to get the code below working. 我正在尝试使下面的代码工作。 It's a finite state machine where I pass in a function-as-next-state. 这是一个有限状态机,我在其中传递了功能为下一个状态。 The function is called with r and returns a list of results + the next function-as-next state. 该函数用r调用,并返回结果列表和下一个作为下一个函数的状态。 Keep on calling until the list runs out, and return the concatenation of the results. 继续调用直到列表用完,然后返回结果的串联。 The monad is an error monad to allow me to throw an error if needed. monad是一个错误monad,如果需要的话,允许我抛出一个错误。

fsm f []     = return []
fsm f (r:rs) = do
    (xs, f') <- f r
    rest     <- fsm f' rs
    return $ xs ++ rest

The error is: 错误是:

Occurs check: cannot construct the infinite type: t1 = t0 -> m0 ([a0], t1)
In the first argument of `fsm', namely f'

I've seen the infinite type error before and I understand the way around it is to wrap a type with a newtype . 我之前见过无限类型错误,并且我了解解决此问题的方法是用newtype包装类型。 But I cannot figure out how to get this done. 但是我不知道如何完成这项工作。

Can someone point out the insight? 有人可以指出这些见解吗?

I think this is what you want: 我认为这是您想要的:

newtype F m = F { unF :: String -> m ([String], F m) }

fsm :: (Monad m) => F m -> [String] -> m [String]
fsm f []     = return []
fsm f (r:rs) = do
    (xs, f') <- unF f r
    rest     <- fsm f' rs
    return $ xs ++ rest

You are right that you need to use a data or newtype any time you want a recursive type. 正确的newtype是,只要需要递归类型,就需要使用data或新类型。

In reply to your comment, here's how you would implement your dup function: 为了回应您的评论,以下是实现dup功能的方法:

dup :: (Monad m) => F m
dup = F dup' where dup' xs = return ([xs, xs], F dup')

... or you could split it up into two separate definitions if you prefer. ...或者您可以根据需要将其分为两个单独的定义。

Note that if you are not sure what the type signature should be, just enable the NoMonomorphismRestriction extension and the compiler will not complain and correctly infer the top-level type for you. 请注意,如果不确定类型签名应该是什么,只需启用NoMonomorphismRestriction扩展,编译器就不会抱怨并正确地为您推断顶级类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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