Haskell:(+ 1)和(\ x-> x + 1)有什么区别?

Nik*_*tov 13 haskell functional-programming

这两个功能有区别吗?

ghct说:

Prelude> :t (+1)
(+1) :: Num a => a -> a
Prelude> :t \x->x+1
\x->x+1 :: Num a => a -> a
Run Code Online (Sandbox Code Playgroud)

当我在这段代码中使用(+ 1)语法时:

data B = B { 
    pos :: Int, 
    cells :: [Int] 
} deriving (Show)

createB :: Int -> B
createB n = B 0 (take n $ repeat 0)

size :: B -> Int
size b = length $ cells b

get_curr :: B -> Int
get_curr b = (cells b) !! (pos b)

apply :: (Int -> Int) -> B -> B
apply f b = let n = pos b
                h = take n $ cells b       -- head
                t = drop (n + 1) $ cells b -- tail
                in B n $ h ++ [f (get_curr b)] ++ t

-- ...
eval :: [Char] -> StateT B IO ()
eval [] = return ()
eval (x:xs) = do
                b <- get

                put $ case x of
                        '+'         -> apply (+1) b
                        '-'         -> apply (-1) b
                        '>'         -> fwd b
                        '<'         -> back b
                        otherwise   -> b
                -- ...
Run Code Online (Sandbox Code Playgroud)

前奏曲(以及编译器)说:

> :load BrainFuck.hs 
[1 of 1] Compiling BrainFuck        ( BrainFuck.hs, interpreted )

BrainFuck.hs:49:40:
    No instance for (Num (Int -> Int))
      arising from the literal `1'
    Possible fix: add an instance declaration for (Num (Int -> Int))
    In the expression: 1
    In the first argument of `apply', namely `(- 1)'
    In the expression: apply (- 1) b
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?抱歉,如果代码不那么酷(这里有完整的来源:https://github.com/nskeip/bf/blob/a755b2d27292593d63fe1e63c2a6e01cebc73520/BrainFuck.hs)

dfl*_*str 22

这段代码:

(-1)
Run Code Online (Sandbox Code Playgroud)

...并不代表与此代码相同的东西:

\ x -> x - 1
Run Code Online (Sandbox Code Playgroud)

-是Haskell的一个特例; 它是该语言中唯一的前缀运算符.当你写作时(-1),你得到的是"负一号",这是一个数字,而不是"减去一个"这是一个函数.

你应该subtract 1用来获得你需要的东西.

  • 您也可以使用`pred`,但请注意`pred minBound`将抛出异常,而`减去1 minBound`将会回绕. (4认同)

Jon*_*oni 11

你的问题不在于(+1),它与(-1):

Prelude> :t (-1)
(-1) :: Num a => a
Run Code Online (Sandbox Code Playgroud)

-1是一个数字!尝试用apply (\x -> x-1) bapply (subtract 1) b.