2

I am new to Haskell.

I have this code (my solution to one of the exercise from Ninety-Nine Haskell Problems)

data Structure a = Single a | Multiple (a, Int) deriving (Show) 

encodeM ::(Eq a)=> [a]->[Structure a]

encodeM l = map(\x -> (let size = length x
            --h = head x
            in if size>1 then Multiple ( head x, size) else Single (head x)
            )
          ) $ group l

When I uncomment "-h = head x" I get: "parse error on input `='"

But

xxx l= let size = length l  
   h = head l
      in  size

works fine, why it doesn't compile when I use "let" with multiple statement inside the lambda?

I have tried to replace let by where

encodeM2 ::(Eq a)=> [a]->[Structure a]

encodeM2 l = map(\x->if si>1 then Multiple ( head x, si) else Single (head x)
   where si = length x)

but it doesn't compile as well, whats wrong with it?

4

3 回答 3

12

这是您正确缩进的代码:(注意let绑定如何垂直对齐)

encodeM :: Eq a => [a] -> [Structure a]
encodeM l = map (\x -> let size = length x
                           h = head x in
                       if size > 1
                          then Multiple (h, size)
                          else Single h) $
              group l

这是您的代码可读:

encodeM :: Eq a => [a] -> [Structure a]
encodeM = map runLength . group
  where
    runLength x =
      let size = length x
          h = head x in
      if size > 1
         then Multiple (h, size)
         else Single h

这是您的代码惯用语:

encodeM :: Eq a => [a] -> [Structure a]
encodeM = map runLength . group
  where
    runLength [x] = Single x
    runLength xs = Multiple (head xs, length xs)
于 2013-06-10T22:25:39.933 回答
4

我更喜欢对 if/then/else 使用模式匹配,因此您的代码变为:

encodeM :: (Eq a) => [a] -> [Structure a]
encodeM lst = map fun $ group lst
              where
                fun [x] = Single x
                fun l = Multiple (head l, length l)
于 2013-06-11T04:30:28.453 回答
2

在 Haskell中,空格很重要

对齐您的let. 而且你不能where在 lambda 中使用。

于 2013-06-10T21:27:10.890 回答