[英]Why use null function instead of == [] to check for empty list in Haskell?
[英]Haskell: Function receiving a null list
这是我的程序供参考的一些类型定义:
type BitString -> String
type Plateau -> [BitString]
我有一个函数叫做:
--Extract will take a list of lists, and return the inner list of the most items. Empty list should return ["00000"]
extract::[Plateau]->Plateau
extract _ = ["00000"]
extract (x:xs)
|x==maximumBy(compare `on` length)xs=x --thanks SOF
|otherwise = extract (xs)
问题是,无论我做什么,提取都会返回["00000"]
以下是GHCI的一些有效输出:
>plateau graycodes
[["01000"],["01010","11010","10010"],["00101"],["01101","01001"]]
这是预期的,并且采用[Plateau]
的形式,因为这是字符串列表的列表。
>maximumBy(compare `on` length)(plateau graycodes)
["01010","11010","10010"]
>extract (plateau graycodes)
["00000"]
在这种情况下,我肯定知道将使用不为空的[Plateau]
调用提取。 但是函数的_
部分正在返回。
我也尝试过:
extract (x:xs)
|x==[]=["00000"]
|x==[""]=["00000"]
|x==maximumBy(compare `on` length)xs=x --thanks SOF
|otherwise = extract (xs)
error: List.maximumBy: Empty list
当您定义具有多个模式的函数时,将按从上到下的顺序尝试它们。 问题是您extract
的最上层模式将匹配任何内容 ,因此将始终选择第一种情况。
解决方案是重新排序它们,或更改第一个模式以仅匹配空列表:
extract [] = ["00000"]
extract (x:xs) = ...
您收到该错误,因为您没有将列表(x:xs)
传递给maximumBy:
extract :: [Plateau] -> Plateau
extract (x:xs)
|x == maximumBy (compare `on` length) (x:xs) = x
|otherwise = extract (xs)
extract _ = ["00000"]
或者,最好是
extract :: [Plateau] -> Plateau
extract s@(x:xs)
|x == maximumBy (compare `on` length) s = x
|otherwise = extract (xs)
extract _ = ["00000"]
(这还会在您的otherwise
后添加一个需要的=
)
编辑:
我对我的答案或您对该答案的接受不满意。
我相信这是您真正需要的代码:
extract :: [Plateau] -> Plateau
extract (x:[]) = x
extract s@(x:xs) = maximumBy (compare `on` length) s
extract _ = ["00000"]
解决方法很简单,提取情况下切换位置。 模式extract _
将始终匹配,因此将永远不会执行第二种情况。
工作代码(希望如此):
--Extract will take a list of lists, and return the inner list of the most items. Empty list should return ["00000"]
extract::[Plateau]->Plateau
extract (x:xs)
|x==maximumBy(compare `on` length)=x --thanks SOF
|otherwise extract (xs)
extract _ = ["00000"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.