【发布时间】:2016-03-04 09:06:52
【问题描述】:
我最近开始阅读 Keets Doets 和 Jan van Eijck 所著的 The Haskell Road to Logic, Maths and Programming 一书(非常非常好的书)。
在其中一项练习中,任务是定义子字符串:我的解决方案有效 并且比作者的要短得多,但是我并不幻想谁是更好的逻辑学家。
那么,我错过了什么:
prefix :: String -> String -> Bool
prefix [] y = True
prefix x [] = False
prefix (x:xs) (y:ys) = (x == y) && (prefix xs ys)
substring :: String -> String -> Bool
substring x [] = False
substring x (y:ys) | prefix x (y:ys) = True
| otherwise = substring x ys
-- Thought the answer provided was a bit overdone
substring' :: String -> String -> Bool
substring' [] ys = True
substring' (x:xs) [] = False
substring' (x:xs) (y:ys) = ((x==y) && (prefix xs ys)) || (substring' (x:xs) ys)
亲切的问候奥克
【问题讨论】:
-
你的解决方案有一个小错误,
substring [] []是错误的。当您考虑修复时,它并不比其他解决方案短得多。他们本可以使用prefix (x:xs) (y:ys)而不是((x==y) && (prefix xs ys)),这样会更好一些。 -
谢谢威廉,很好的回答。这真是令人愉快的大脑锻炼:)
标签: haskell