2016-12-07 9 views
-2
import Data.List 
import System.IO 

import Data.STRef 
import Data.Char 

main = do 
     let x = dup 'a' "the cat in the hat has a fat head" 
     putStrLn $ show $ x 

に与えられた文字のすべての出現を複製Haskellの関数を書くにはどうすればよい、私は私はこれは私がこれまで持っているものである文字列

+7

ようこそスタックオーバーフロー!私は間違っているかもしれませんが、これは問題文のように見えます。テストケースでさえ、試みはしません。なぜあなたはこれをあなた自身で解決しようとしていて、どこにいらっしゃったのか見ていないのですか? :) – Alec

答えて

1

あなたは:を使用することができ、ここでフォームどこへ行くかわかりませんxと尾を頭にパターンマッチにリスト

  • x:xsでリストを作業する機能を記述するときxs
  • x:xsからリストを作成しますとxs

dup関数を記述するために多くの方法がありますが、これは|

dup :: Char -> String -> String 
dup c [] = [] 
dup c (x:xs) 
    | c == x = x:x:dup c xs 
    | otherwise = x:dup c xs 

main = do 
    let x = dup 'a' "the cat in the hat has a fat head" 
    putStrLn x 

ガードを使用して、私の迅速な解決策である

the caat in the haat haas aa faat heaad 
0

にこれを行うには非常に多くの方法を与えます;)、例えば

dup :: Char -> String -> String 
dup charToDup s = concatMap dupC s 
    where dupC c = if c == charToDup then replicate 2 c 
       else [c] 
1

リストの理解度を使用して解決できます。

dup :: Char -> [Char] -> [Char] 
dup c string = [ ss | s <- string, ss <- if c == s then [c] ++ [s] else [s]] 
関連する問題