1

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

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]

请帮忙!!

4

4 回答 4

1

列表理解让生活更轻松

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

lang是多态的,如果这是不可取的,只需添加一个类型签名。

于 2013-10-01T22:05:22.383 回答
0
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

use

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

to get

["ad","ae","af","bd","be","bf","cd","ce","cf"]
于 2013-10-01T06:34:51.223 回答
0

Classic example where Applicative Functors can come in handy:

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

You should definitely check out Aplicative Functors for this ...

于 2014-02-01T03:35:56.400 回答
0

concat_lang xs ys = [ x++y | x <- xs, y <- ys]

于 2014-02-01T03:01:18.440 回答