首页 \ 问答 \ Haskell代码中反斜杠的含义?(Meaning of backslash in Haskell code?)

Haskell代码中反斜杠的含义?(Meaning of backslash in Haskell code?)

所以我有这个haskell代码,我理解它的一半,但我不能理解这个\x ->这里:

testDB :: Catalogue
testDB = fromList [
 ("0265090316581", ("The Macannihav'nmor Highland Single Malt", "75ml bottle")),
 ("0903900739533", ("Bagpipes of Glory", "6-CD Box")),
 ("9780201342758", ("Thompson - \"Haskell: The Craft of Functional Programming\"", "Book")),
 ("0042400212509", ("Universal deep-frying pan", "pc"))
 ]


-- Exercise 1

longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (\(x, y) -> length $ fst y) 

formatLine :: Int -> (Barcode, Item) -> String
formatLine k (x, (y1, y2)) = x ++ "..." ++ y1 ++ (take  (k - length y1) (repeat '.')) ++ "..." ++ y2

showCatalogue :: Catalogue -> String
showCatalogue c = foldr (++) "" $ map (\x -> (formatLine (longestProductLen (toList testDB)) x) ++ "\n") $ toList c

我知道longestProductLen返回并且整数意味着testDB最长的标题,然后它使用这个整数来匹配formatLine中的k ,但是我(Bardcode, Item)它是如何匹配的(Bardcode, Item)我想它与\x -> ,如果可以,请解释一下它是如何做到的?

谢谢!


So I have this haskell code, and I understand half of it, but I can't get my head around this \x -> here:

testDB :: Catalogue
testDB = fromList [
 ("0265090316581", ("The Macannihav'nmor Highland Single Malt", "75ml bottle")),
 ("0903900739533", ("Bagpipes of Glory", "6-CD Box")),
 ("9780201342758", ("Thompson - \"Haskell: The Craft of Functional Programming\"", "Book")),
 ("0042400212509", ("Universal deep-frying pan", "pc"))
 ]


-- Exercise 1

longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (\(x, y) -> length $ fst y) 

formatLine :: Int -> (Barcode, Item) -> String
formatLine k (x, (y1, y2)) = x ++ "..." ++ y1 ++ (take  (k - length y1) (repeat '.')) ++ "..." ++ y2

showCatalogue :: Catalogue -> String
showCatalogue c = foldr (++) "" $ map (\x -> (formatLine (longestProductLen (toList testDB)) x) ++ "\n") $ toList c

I understand that longestProductLen returns and integer meaning the longest title in testDB and then it uses this integer to match k in formatLine, but I can't understnad how it matches (Bardcode, Item) and I guess it has something to do with \x ->, if it does can you please explain how it does that?

Thank you!


原文:https://stackoverflow.com/questions/34794132
更新时间:2021-06-07 19:06

最满意答案

语法

function x y = <body>

相当于

function = \x y -> <body>

并称为lambda或匿名函数。 编译器实际上将所有函数转换为lambda函数的赋值(第二种形式),因为它只是给函数值(函数是Haskell中的值)一个名称。

如果你看到它作为另一个函数的参数给出,比如map

map (\x -> x + 1) [1, 2, 3]

这在语义上等同于

map add1 [1, 2, 3] where add1 x = x + 1

Lambdas也可以对其参数执行任意模式匹配。 另外,如果你有一个像这样的定义

fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

这相当于

fib = \n -> case n of
    0 -> 1
    1 -> 1
    n -> fib (n - 1) + fib (n - 2)

因为编译器将首先将多个模式匹配转换为case语句,然后将其转换为将lambda指定给名称(在这种情况下将lambda指定为名称fib )。


The syntax

function x y = <body>

Is equivalent to

function = \x y -> <body>

And is called a lambda or anonymous function. The compiler actually turns all your functions into assignments of lambda functions (the second form) since it's just giving a function value (functions are values in Haskell) a name.

If you see it given as an argument to another function like map:

map (\x -> x + 1) [1, 2, 3]

This is semantically equivalent to

map add1 [1, 2, 3] where add1 x = x + 1

Lambdas can perform arbitrary pattern matching on their arguments, too. Also, if you have a definition like

fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

This is equivalent to

fib = \n -> case n of
    0 -> 1
    1 -> 1
    n -> fib (n - 1) + fib (n - 2)

Because the compiler will first translate the multiple pattern matching into a case statement, then convert it to assigning a lambda to a name (in this case assigning the lambda to the name fib).

相关问答

更多

Haskell - 字面反斜杠总是必须在字符串中转义吗?(Haskell - Do literal backslashes always have to be escaped in a string?)

不,请参阅Haskell词汇结构 2.6节。 Haskell没有原始字符串,heredocs或三重字符串。 抱歉。 你唯一的幻想是这样的: "ab\ \cd" => "abcd" 行尾和斜杠之间的空白被忽略。 例如,如果您想要发出一些在Haskell源代码中正确缩进但不会在输出中过度缩进的内联HTML,这很有用。 (并不是说我会主张通过这种方式来完成复杂的HTML输出。) No, see section 2.6 of Haskell Lexical Structure. Haske ...

Haskell运算符“<>”的含义是什么?(What is the meaning of the Haskell operator “<>”?)

这是来自Data.Monoid模块的Data.Monoid的别名。 (<>) :: Monoid m => m -> m -> m (<>) = mappend mappend两个mappend值一起打碎。 例如,使用列表monoid, ghci> [1,2,3] <> [4,5,6] [1,2,3,4,5,6] 当你看到一个你不认识的函数时,你可以在Hoogle或Hayoo等API搜索引擎上找到它。 It's an alias for mappend, from the Data.Monoi ...

Haskell中<= vs. =>的含义(The meaning of <= vs. => in Haskell)

这两者完全不相关; 它们似乎因为ASCII而相关。 如果你看看它们的Unicode等价物会更有意义: =>是一个箭头: ⇒ 。 它用于在类型签名中指定约束: Eq a => a -> a -> Bool 上述签名中的Eq a =>表示类型变量a可以是作为Eq类的实例的任何类型。 也就是说,任何具有deriving (Eq)或显式实例的instance Eq Type where ...如instance Eq Type where ... 在函数签名中, ->指定正常参数,而=>指定签名中的约束 ...

对python中的反斜杠感到困惑(Confused about the backslash in python)

请查看https://docs.python.org/2.0/ref/strings.html以获得更好的解释。 第二个例子的问题是string不是原始字符串,所以\'被解释为' 。 如果您将其更改为: >>> not_raw = 'adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .' >>> res1 = re.search ...

使用ShowString在haskell中打印单个反斜杠(Printing a single backslash in haskell using ShowString)

您可能想要使用: putStrLn (showString "\\" []) 在GHCi REPL中,当您输入一个值,而不是IO动作时,将使用show自动呈现,然后将show某些字符。 例如: Prelude> showString "\\" [] "\\" Prelude> putStrLn $ showString "\\" [] \ You probably want to use: putStrLn (showString "\\" []) Within the GHCi REPL ...

Haskell代码中反斜杠的含义?(Meaning of backslash in Haskell code?)

语法 function x y = <body> 相当于 function = \x y -> <body> 并称为lambda或匿名函数。 编译器实际上将所有函数转换为lambda函数的赋值(第二种形式),因为它只是给函数值(函数是Haskell中的值)一个名称。 如果你看到它作为另一个函数的参数给出,比如map : map (\x -> x + 1) [1, 2, 3] 这在语义上等同于 map add1 [1, 2, 3] where add1 x = x + 1 Lambdas也可 ...

了解haskell代码(Understanding haskell code)

-- Filter a list... filter -- ...of nested tuples where the first element of the second element of the tuple... (\(_, (variable1, _)) -> -- ...is not an element of [something1, something2] variable1 `notElem` [something1, something2]) (_, (varible ...

haskell正则表达式替换:模式包含反斜杠(haskell regex replace: pattern contains backslash)

在你的python中,你有一个原始字符串 : r"(\\mbfA)(\W)" - 这意味着反斜杠只是一个反斜杠,而不是一个转义字符。 但是在你的Haskell代码中,你需要使用反斜杠转义反斜杠,当你需要在正则表达式中使用双反斜杠时,你需要在字符串中使用四个反斜杠。 这应该是这样的: makeRegex "(\\\\mbfA)([^[:alnum:]])" :: Regex In your python, you've got a raw string: r"(\\mbfA)(\W)" - whi ...

Haskell中的反斜杠空间是什么意思(What does backslash space mean in Haskell)

没有区别: \ r -> x或\r -> x具有相同的含义,很多1+1和1 + 1具有相同的含义。 \之后的空格是不相关的。 所以, return x就是\r -> x ,它是一个函数,它接受一个参数r ,忽略它并产生x 。 而且,由于r被忽略,我们倾向于写成\ _ -> x (或const x - 它被定义为const x _ = x )。 There is no difference: \ r -> x or \r -> x have the same meaning, much as 1+1 ...

在Haskell中导出Read(和Show)时,避免使用反斜杠编码utf8字符(Avoid backslash-encoding utf8 characters when deriving Read (and Show) in Haskell)

据我所知, Text使用的内部编码( 实际上是UTF-16 )是一致的,不会直接暴露。 如果需要UTF-8,可以根据需要对Text值进行解码/编码。 类似地,谈论String的编码没有意义,因为这只是Char的列表,其中每个Char是一个unicode代码点。 最有可能的是,只有Text的Show实例在这里以不同的方式显示。 另外,请记住(通过标准库中的一致约定) read和show应该表现为(de-)序列化函数,使用“序列化”格式,解释为Haskell表达式,描述一个等价于一个的值被(去)序列化 ...

相关文章

更多

最新问答

更多
  • 如何从远程文件拉取文件而不覆盖本地文件?(How do I pull files from remote without overwriting local files?)
  • Reactjs:状态改变时重新渲染iframe(Reactjs: re-renders iframes when state changed)
  • 奇怪的网址,以及跟随php页面流程的困难(odd url, and difficulty in following the php page flow)
  • 标签活动无效(Tab Activity is not working)
  • JavaME合适的语法编译器建议?(JavaME-suitable grammar compiler recommendations?)
  • 指定参数(Specifying arguments)
  • 可以通过Ruby插件或控制台覆盖Sketchup中的键盘快捷键吗?(Can one override keyboard shortcuts in Sketchup through the a Ruby Plugin or Console?)
  • 计算Java EE Web App中用户数的最佳方法(Best way to count number of users in a Java EE web App)
  • 无法使用templateUrl加载cordova中的外部模板(unable to load external templates in cordova with templateUrl)
  • PHPExcel:写入期间无法使用缓存(PHPExcel: Unable to use cache during write)
  • 在javascript中嵌套这个指针(nested this pointer in javascript)
  • 谁跟领航致远培训过,有问题问下啊
  • 控制器要求在入门时下载(Controller ask to download on entry)
  • 未能通过conda安装Asyncio(Failure to install Asyncio via conda)
  • 如何查找已完成项目的总长度?(How to find length of total completed items?)
  • 如何检查OleInitialize是否已被调用?(How to check if OleInitialize has already been called?)
  • SQL在特定范围内返回列中具有最大值的行(SQL Returning rows with max value in column, within a specific range)
  • preg_match从url获取id(preg_match get the id from url)
  • 如何在运算符中为make方程转换perl变量?(How to convert a perl variable in a operator for make equations?)
  • 在导航上方添加空格/标题。(Add a white space/ header above navigation.)
  • MeetingItem已保存;(MeetingItem saved; but change now shown in Calendar)
  • c#vb:我们应该使用System.Lazy进行资源密集型任务吗?(c# vb: Should we use System.Lazy for resource-intensive task? (when threading is not needed))
  • 为什么在armeabi代码中使用armeabi-v7a代码?(Why use armeabi-v7a code over armeabi code?)
  • 获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))
  • 是否可以在嵌套的if语句中从varchar转换为numeric以动态评估参数?(Is it possible to convert from varchar to numeric within a nested if statement in order to dynamically evaluate a parameter?)
  • 如何将Html.ActionLink转换为链接到Ajax调用的按钮?(How to convert from Html.ActionLink to a button linked to Ajax call?)
  • 应用程序如何处理Windows符号链接?(How are Windows symbolic links treated by the apps?)
  • html,js,css在jsfiddle中工作,但不在sharepoint中(html, js, css works in jsfiddle but not in sharepoint)
  • 从Ruby脚本调用Elasticsearch Rest API(Calling Elasticsearch Rest API from Ruby script)
  • 如何将嵌套setTimeouts转换为承诺(How to convert nested setTimeouts to promises)