在Haskell中实现tails函数

Ash*_*win 1 haskell

我正在尝试实现该功能tails.这是我的尝试:

tails' :: [a] -> [[a]]
tails' [] = []
tails' (x:xs) = xs:[[tails' xs]]
Run Code Online (Sandbox Code Playgroud)

我一直遇到编译错误:

Couldn't match expected type ‘a’ with actual type ‘[[a]]’
      ‘a’ is a rigid type variable bound by
          the type signature for tails' :: [a] -> [[a]] at..
Run Code Online (Sandbox Code Playgroud)

我的实施有什么问题?

Lea*_*van 6

更换

tails' (x:xs) = xs:[[tails' xs]]
Run Code Online (Sandbox Code Playgroud)

有:

tails' (x:xs) = xs : tails' xs
Run Code Online (Sandbox Code Playgroud)

  • 你甚至不需要parens:`xs:tails'xs`工作正常. (2认同)
  • 另一个狡辩 - 与 `Data.List.tails` 相同,`head (tails xs) == xs` (2认同)

kar*_*kfa 5

除了语法类型错误之外,您的实现不正确(符合规范)。对比一下这个...

Prelude> let tails [] = [[]]
Prelude|     tails y@(x:xs) = y:(tails xs)
Prelude|
Prelude> tails "abc"
["abc","bc","c",""]
Run Code Online (Sandbox Code Playgroud)