基本例程实现的“纯”函数式编程有多好,例如列表排序、字符串匹配等?
在任何函数式语言的基本解释器中实现这些基本功能是很常见的,这意味着它们将用命令式语言 (c/c++) 编写。虽然有很多异常(exception)..
至少,我想问:在用“纯”函数式语言编码时模拟命令式风格有多难?
最佳答案
How good is 'pure' functional programming for basic routine implementations, e.g. list sorting, string matching etc.?
非常。我会在 Haskell 中解决你的问题,我会稍微详细介绍一下。我的目的不是让你相信这个问题可以用 5 个字符来完成(它可能可以用 J!),而是让你了解这些结构。
import Data.List -- for `sort`
stdlistsorter :: (Ord a) => [a] -> [a]
stdlistsorter list = sort list
使用
sort
对列表进行排序函数来自 Data.List
import Data.List -- for `delete`
selectionsort :: (Ord a) => [a] -> [a]
selectionsort [] = []
selectionsort list = minimum list : (selectionsort . delete (minimum list) $ list)
选择排序实现。
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
快速排序实现。
import Data.List -- for `isInfixOf`
stdstringmatch :: (Eq a) => [a] -> [a] -> Bool
stdstringmatch list1 list2 = list1 `isInfixOf` list2
使用
isInfixOf
进行字符串匹配函数来自 Data.list
It's common to implement such basic functions within the base interpreter of any functional language, which means that they will be written in an imperative language (c/c++). Although there are many exceptions..
要看。有些函数更自然地用命令式表达。但是,我希望我已经说服了您,有些算法也以函数方式自然表达。
At least, I wish to ask: How difficult is it to emulate imperative style while coding in 'pure' functional language?
这取决于你在 Haskell 中找到 Monads 的难度。就个人而言,我觉得很难掌握。
关于functional-programming - 基本算法的函数式编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1535741/