Haskell在lambda中的多个绑定

时间:2013-06-10 21:23:20

标签: haskell

我是Haskell的新手。

我有这个代码(我对Ninety-Nine Haskell问题的一个练习的解决方案)

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

当我取消注释“-h = head x”时,我得到:“输入`='上的解析错误”

但是

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

工作正常,为什么当我在lambda中使用带有多个语句的“let”时它不能编译?

我试图将地方替换为

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)

但它也没有编译,它有什么问题吗?

3 个答案:

答案 0 :(得分:11)

这是你的代码正确缩进:(注意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)

答案 1 :(得分: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)

答案 2 :(得分:2)

在Haskell whitespace matters

对齐let中的作业。你不能在lambda中使用where