List 为什么字符串列表突然变成了字符串列表?
我有一个功能:List 为什么字符串列表突然变成了字符串列表?,list,haskell,types,List,Haskell,Types,我有一个功能: setDisplays :: Char -> [String] -> IO() setDisplays mode dIds | mode == 'l' = chngDispl (head dIds) | mode == 'e' = chngDispl (tail dIds) where chngDispl on = mapM_ (\id -> callProcess "xrandr" ["--output", id, "--a
setDisplays :: Char -> [String] -> IO()
setDisplays mode dIds
| mode == 'l' = chngDispl (head dIds)
| mode == 'e' = chngDispl (tail dIds)
where
chngDispl on = mapM_ (\id -> callProcess "xrandr" ["--output", id, "--auto"]) on
这将获得一个字符串列表,其中包含xrandr提供的显示ID,如下所示[eDP1,HDMI1]。通过绑定IO将列表传递给setDisplays:
现在,我收到以下错误消息:
解析器.hs:50:37:
Couldn't match type ‘Char’ with ‘[Char]’
Expected type: [[String]]
Actual type: [String]
In the first argument of ‘head’, namely ‘dIds’
In the first argument of ‘chngDispl’, namely ‘(head dIds)’
Failed, modules loaded: none.
我不明白。甚至ghc mod也告诉我,当第一次提到这个名字时,它会标识[String],当我在函数调用中使用ghc mod进行typecheck时,它会标识[[[Char]]。这里发生了什么?您正在正面使用DID,并希望它是一个[String]。因此,类型推断告诉我们,以这种方式使用的DID应该是[[String]]类型
另外,您正在使用下面一行的dIds上的tail。这不匹配。您使用的是正面DID,并希望它是一个[String]。因此,类型推断告诉我们,以这种方式使用的DID应该是[[String]]类型
另外,您正在使用下面一行的dIds上的tail。这不匹配。如果dIds是一个[String],那么head的结果将是一个字符串,但chngDispl需要一个[String]。这就是为什么编译器认为head的参数应该是[[String]]
将head did包装在一个列表中,错误就会消失
您通常应该避免使用头部,而是使用模式匹配。您可以像这样重写函数:
setDisplays :: Char -> [String] -> IO()
setDisplays mode (id:ids)
| mode == 'l' = chngDispl [id]
| mode == 'e' = chngDispl ids
where
chngDispl on = mapM_ (\id -> callProcess "xrandr" ["--output", id, "--auto"]) on
请注意,如果列表为空,但head也为空,则此操作将失败。您还应处理该情况。如果dIds为[String],则head的结果将为字符串,但chngDispl需要[String]。这就是为什么编译器认为head的参数应该是[[String]]
将head did包装在一个列表中,错误就会消失
您通常应该避免使用头部,而是使用模式匹配。您可以像这样重写函数:
setDisplays :: Char -> [String] -> IO()
setDisplays mode (id:ids)
| mode == 'l' = chngDispl [id]
| mode == 'e' = chngDispl ids
where
chngDispl on = mapM_ (\id -> callProcess "xrandr" ["--output", id, "--auto"]) on
请注意,如果列表为空,则此操作将失败,但head也将失败,您也应处理此情况。type String=[Char]type String=[Char]此外,head通常是邪恶的。这个问题不是真正的原因之一,但它也增加了证据。头应该改名为邪恶头,以更清楚地反映它的邪恶:而且,头通常是邪恶的。这个问题不是真正的原因之一,但它也增加了证据。头应该改名为邪恶头,以更清楚地反映它的邪恶:。。。更好的是,使用模式匹配并去掉head。@JanGreve我添加了一个模式匹配的示例。。。。更好的方法是使用模式匹配并去掉head。@JanGreve我添加了一个模式匹配的例子。