我如何将变量带入范围,以及如何匹配类型

问题描述 投票:1回答:1

每次尝试加载包含func1的模块时,我都会遇到错误,并且我不知道如何解决。

func2和func3独立工作,并且完全按照他们的预期去做。

func1 xs = [x| let x = func2 (-c) xs, (_,c) <- func3 xs] 

func1需要一个字符串,并且应该传递另一个字符串。 xs是输入String,x是输出String。 func 2需要一个Int和String,c是一个Int,并生成另一个String。 func3需要一个字符串,并输出一个元组。 (_,c)是输出,第一个元素是_,因为它与该函数无关,而第二个元素是整数。

没有输出,并且收到以下错误消息:

Programm.hs:205:18: error:
    Variable not in scope: c :: Integer
    |
205 |         func2 (-c) xs
    |                  ^

Programm.hs:208:16: error:
    * Couldn't match type `[Char]' with `Char'
      Expected type: Char
        Actual type: String
    * In the expression: x
      In the expression:
        [x | let x = func2 (- c) xs, (_, c) <- func3 xs]
      In an equation for `decypher':
          func1 xs = [x | let x = func2 (- c) xs, (_, c) <- func3 xs]
    |
208 | func1 xs = [x| let x = func2 (-c) xs, (_,c) <- func3 xs]
    |                

Programm.hs:208:36: error:
    Variable not in scope: c :: Int
    |
208 | func1 xs = [x| let x = func2 (-c) xs, (_,c) <- func3 xs]
    |                                    
Failed, no modules loaded.

现在,我的问题是:当我将c定义为func3输出的第二个元素时,为什么c并不是整数(我也用“ let(_,c)= func3 xs”尝试过),哪个一定是整数?

当func2的输出必须为String时,为什么期望x为Char?

先谢谢您,请耐心等待,我正在学习Haskell:*

haskell ghc ghci
1个回答
0
投票

您应该将let子句和generator子句的顺序交换为:

func1 xs = [ x | (_,c) <- func3 xs, let x = func2 (-c) xs ]

但是由于您仅在列表理解的“收益”部分中使用x,因此您可以简单地省略let x = …,并使用:]]

func1 xs = [ func2 (-c) xs | (_,c) <- func3 xs ]

基于signatures of your function

func1 :: String -> String
func2 :: Int -> String -> String
func3 :: String -> (Float,Int)

您的func3不返回列表:它返回一个2元组。在这种情况下,您的func1应该看起来像:

func1 :: String -> String
func1 = negate . snd . func3 >>= func2

或更简单:

func1 :: String -> String
func1 xs = func2 (- (snd (func3 xs))) xs
© www.soinside.com 2019 - 2024. All rights reserved.