小编asp*_*sp5的帖子

了解递归的Haskell/GHCI行为

我试图通过以下功能理解我所看到的内容.不确定我的理解是否不正确,或者这是否是特定于Haskell的GHC实现的行为.

countNumLastChar :: Eq a => [a] -> (a, Int)
countNumLastChar [x]      = (x, 1)
countNumLastChar (x:xs)  = if x == fst y
                            then (fst y, (snd y) + 1)
                            else y
                            where y = countNumLastChar xs
Run Code Online (Sandbox Code Playgroud)

我正在看到一些我无法用这段代码解释的东西.

*Main> countNumLastChar "aba"
('a',2)
*Main> countNumLastChar "abql;kejrqlwkjer;lqwkejr;lwjerca"
('a',2)
*Main> countNumLastChar "abql;kejrqlwkjer;lqwkejr;lwjercap"
('p',1)
*Main> countNumLastChar "abql;kejrqlwkjer;lqwkejr;lwjerca;"
(';',4)
Run Code Online (Sandbox Code Playgroud)

例如:使用GHCI跟踪下面的运行,我看到当我们使用尚未重复的元素到达单例列表时,我们不会递回每一步.

*Main> countNumLastChar "aabc"
('c',1)
[maxOccurCharInStr.hs:(3,28)-(5,34)] *Main> :step
Stopped at maxOccurCharInStr.hs:3:31-40
_result :: Bool = _
x :: Char = 'b'
y :: (Char, Int) = …
Run Code Online (Sandbox Code Playgroud)

recursion haskell

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

Haskell:GHCI中错误的含义

我无法弄清楚msg的这个错误意味着什么.我想在下面定义数据类型的函数距离...我不想使用任何GHC扩展..即使代码很难看,想要在继续​​使用扩展之前更好地理解错误.有人可以让我知道这个错误意味着什么,以及如何摆脱这个.

class Vector v where

         distance :: v -> v -> Double

-- doesn't make sense, but WTH...    
newtype OneD1 a = OD1 a
         deriving (Show)

instance Vector (Maybe m) where
    distance _ _ = 5.6

instance Vector (OneD1 m) where
   distance (OD1 x1) (OD1 x2) = x2-x1

    Prelude> :reload
[1 of 1] Compiling Main             ( VectorTypeClass.hs, interpreted )

VectorTypeClass.hs:33:33:
    Couldn't match expected type `Double' with actual type `m'
      `m' is a rigid type variable bound by
          the instance declaration …
Run Code Online (Sandbox Code Playgroud)

haskell

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

标签 统计

haskell ×2

recursion ×1