【问题标题】:haskell language concatenationhaskell 语言连接
【发布时间】:2013-10-01 04:07:51
【问题描述】:

这是我的任务,字符串连接函数在下面,下面是我需要帮助的函数。

type Language = [String]
strcat :: String -> String -> String
strcat [] y     = y
strcat (x:xs) y = x:(strcat xs y)

concat_lang :: Language -> Language -> Language
concat_lang [] y = y
concat_lang x [] = x
concat_lang (x:xs) (y:ys) = (strcat x y):(concat_lang (x:xs) ys)

这是我对 concat_lang 的输入: concat_lang ["a","b","c"] ["d","e","f"]

我希望输出为 [ad,ae,af,bd,be,bf,cd,ce,cf]

请帮忙!!

【问题讨论】:

  • 提示:使用列表理解和(++concat)。
  • 你几乎明白了。您的strcat 是正确的,但您在concat_lang 中存在问题 - 它永远不会移动到xs 中的下一个字符。您需要更多提示吗?

标签: list haskell string-concatenation


【解决方案1】:

列表理解让生活更轻松

lang xs ys = [x:y:[] | x <- xs , y <- ys]

lang 是多态的,如果不希望这样做,只需添加类型签名。

【讨论】:

    【解决方案2】:
    combinations :: [a] -> [b] -> [(a,b)]
    combinations xs ys = concatMap (flip zip ys . repeat) xs
    
    
    type Language = [String]
    
    concat_lang :: Language -> Language -> Language
    concat_lang xs ys = map f $ combinations xs ys
        where
            f (x,y) = x ++ y
    

    使用

    concat_lang ["a","b","c"] ["d","e","f"]
    

    得到

    ["ad","ae","af","bd","be","bf","cd","ce","cf"]
    

    【讨论】:

      【解决方案3】:

      concat_lang xs ys = [ x++y | x

      【讨论】:

        【解决方案4】:

        Applicative Functor 可以派上用场的经典示例:

        >> import Control.Applicative
        >> (++) <$> ["a", "b", "c"] <*> ["d", "e", "f"]
           ["ad","ae","af","bd","be","bf","cd","ce","cf"]
        >> 
        

        您绝对应该为此查看 Aplicative Functors ...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-21
          • 2014-03-13
          • 1970-01-01
          • 2013-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多