小编gau*_*ing的帖子

试图理解为什么在 Haskell 中使用 foldr 的这个函数不起作用

所以我是 Haskell 的新手并使用 WikiBooks 学习它。在高阶函数章节中,使用了以下示例。

echoes = foldr (\ x xs -> (replicate x x) ++ xs) []
Run Code Online (Sandbox Code Playgroud)

所以我尝试运行它,但它给了我如下错误:

 * Ambiguous type variable `t0' arising from a use of `foldr'
  prevents the constraint `(Foldable t0)' from being solved.
  Relevant bindings include
    echoes :: t0 Int -> [Int] (bound at HavingFun.hs:107:1)
  Probable fix: use a type annotation to specify what `t0' should be.
  These potential instances exist:
    instance Foldable (Either a) -- Defined in `Data.Foldable'
    instance Foldable Maybe -- Defined in …
Run Code Online (Sandbox Code Playgroud)

haskell functional-programming higher-order-functions

7
推荐指数
1
解决办法
114
查看次数

理解“if then else”情况下的 Haskell 惰性

目前,我正在尝试通过宾夕法尼亚大学的 FP in Haskell 课程来学习 Haskell。在其中一项作业中,我必须定义以下类型类来实现表达式求值计算器:

class Expr a where
  mul :: a -> a -> a
  add :: a -> a -> a
  lit :: Integer -> a

class HasVars a where
  var :: String -> a
Run Code Online (Sandbox Code Playgroud)

一种模仿数学表达式的数据类型,可以包含整数、加法、乘法,还可以在表达式中保存变量。

data VarExprT = VarLit Integer
              | VarAdd VarExprT VarExprT
              | VarMul VarExprT VarExprT
              | Var String
              deriving (Show, Eq)

instance HasVars VarExprT where
  var = Var

instance Expr VarExprT where
  lit = VarLit
  add = VarAdd
  mul = VarMul

Run Code Online (Sandbox Code Playgroud)

现在,为了模拟表达式中变量的加法、乘法操作,我必须创建上述类型类的实例,如下所示:

instance …
Run Code Online (Sandbox Code Playgroud)

haskell functional-programming lazy-evaluation

0
推荐指数
1
解决办法
219
查看次数