我试图编写一个从Haskell中的String中获取最长数字的函数。
示例:" Test12 Test123 Test1234"
这应返回1234,因为1234是此String中最长的数字。
这就是我的代码目前的样子:
import Data.Char
longNumber :: String -> Int
longNumber n = length (filter ((> 1) . length . filter isDigit) . words) n
有人可以帮我吗?
答案 0 :(得分:1)
看起来你想要这样的东西:
longNumber :: String -> Int
longNumber = read . maximumBy (comparing length) . map (filter isDigit) . words
答案 1 :(得分:0)
使用' takeWhile'功能与' isDigit'和递归。
import Data.Char
import Data.List
import Data.Function
getLongest [] = []
getLongest l = getMax $ getNumbers l []
where getNumbers [] ls = ls
getNumbers l@(x:xs) ls
| isDigit x = getNumbers (dropWhile isDigit l) (ls ++ [takeWhile isDigit l])
| otherwise = getNumbers xs ls
getMax ls = if (ls == []) then [] else (maximumBy (compare `on` length) ls)
答案 2 :(得分:0)
import Data.Char
import Data.Function
import Data.List
takeAllNumbers :: String → [String]
takeAllNumbers "" = []
takeAllNumbers s = let (n,s') = takeNumber s
in n:takeAllNumbers s'
where takeNumber = span isDigit ∘ dropWhile (not ∘ isDigit)
maxNumber :: String → Maybe Int
maxNumber "" = Nothing
maxNumber s = let allNums = takeAllNumbers s
in if null allNums
then Nothing
else Just $ read $ maximumBy (compare `on` length) allNums
函数takeAllNumbers
提取给定字符串中的所有数字,而maxNumber
选择字符串形式中具有最大长度的数字。请注意maxNumber
返回Maybe Int
,因为字符串中可能没有数字。
答案 3 :(得分:0)
您假设数字总是在单独的单词中。如果你的字符串没有空格怎么办? words
函数对您没有帮助,只需删除非数字字符就可能导致问题。例如"ab1c2d3 test12"
将成为`[" 123"," 12"]。
另外,你需要返回一个Maybe Int(如果没有数字会怎么样?)
以下是我对此问题的第一次尝试。
import Data.Ord (comparing)
import Data.Char (isDigit)
import Data.List (maximumBy, null, groupBy)
longestNumber :: String -> Maybe Int
longestNumber s
| null nums = Nothing
| otherwise = Just $ read $ maximumBy (comparing length) nums
where
nums = filter (isDigit . head) groups
groups = groupBy (\a b -> isDigit a == isDigit b) s