2

过去一两周,在我的计算机科学课上,有人要求我们展示如何通过“原则性转换”来简化和缩短函数。我们没有收到关于这些作业的反馈,所以我不知道我是否做得对。

这是我最近的练习,也是我尝试的解决方案:

Show by a series of principled transformations that we can define:
    char :: Char -> Parser Char
    char c = satisfy (c==)
as
    char :: Char -> Parser Char
    char = satisfy . (==)

我的尝试:

char c = satisfy (c==)
=> char c = satisfy . c==
=> char c = satisfy . flip ==c
=> char = satisfy . flip ==
=> char = satisfy . (==)

请问我可以得到一些反馈吗?为分配提供的代码不完整,因此我无法编译它并测试每个转换是否有效。我尝试编写一组类似的函数来自己测试转换,但不幸的是我很不擅长并且对 Haskell 很陌生,所以我也无法弄清楚。

4

2 回答 2

8

这是一个循序渐进的方法:

char c = satisfy (c==)
char c = satisfy (\x -> c == x)   -- Sections [1]
char c = satisfy (\x -> (==) c x) -- Prefix form
char c = satisfy ((==) c)         -- Eta reduction [2]
char c = (.) satisfy (==) c       -- Composition: `(.) f g x = f (g x)`
char c = (satisfy . (==)) c       -- Infix form
char   = satisfy . (==)           -- Eta reduction

我什至可能会放弃明确扩展该部分并简单地从(c==)to 转到((==) c).

1:http
://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-300003.5 2:http ://www.haskell.org/haskellwiki/Eta_conversion

于 2013-11-08T07:15:57.353 回答
3

好吧这里有几个错误,我先写下相关类型

char :: Char -> Parser Char
satisfy :: (Char -> Bool) -> Parser Char
(==) :: Char -> Char -> Char

我特意限制了一些签名以使这更令人愉快。

char c = satisfy (c==)
char c = satisfy . c== -- This is a parse error, not sure what you meant
char c = satisfy . flip ==c -- Also wrong, flip swaps arguments, 
                            -- but this function has only one argument
char = satisfy . flip == -- Eta conversion is right, this code is
                         -- still a parse error - you should check code with ghci or winhugs

我的方法是

char c = satisfy   (c==)
char c = satisfy $ (\c -> \d -> c == d) c -- Explicitly undo sections
char c = satisfy . (\c d -> c == d) $ c -- f(g x) === (f . g) x by the
                                        -- definition of composition
char c = (satisfy . (==)) c
char = satisfy . (==)
于 2013-11-08T04:45:16.393 回答