2017-11-20 4 views
-2

私は2つの文字列(AとB)と構造体(C)を受け取るデータ構造体に関数を記述する際に問題があります。ハスケルのデータ構造体への挿入

目的は、新しい構造Bを作成し、所属する構造A、に挿入することで、またはである、所与の構造C.

だから、それはでA「という名前の」構造を探してください構造体C( "A"が多い場合は、 "最も古い"を選択する必要があります)を見つけたら、新しい構造体Bを作成し、構造体 "A"に追加します。

data Structure = Structure String [Structure] 

instance Show Familia where 
show (Familia a (xs)) = intercalate "\n" $ a : [" " ++ show x | x <- xs] 

insert :: String -> String -> Structure -> Structure 

私はこのコード化されています:

newStrct :: String -> Structure 
newStrct a = Structure a [] 

name :: Structure -> String 
name (Structure a xs) = a 

StrctList :: Structure -> [String] 
StrctList (Structure a []) = [] 
StrctList (Structure a xs) = [nome x | x <- xs] 

search :: String -> Structure -> Structure 
search (Structure b xs) = case (elemIndex a (StrctList (Struture b xs))) of 
    Just n -> xs !! n 
    Nothing -> Structure "Not found" [] 

addToStrct :: String -> Structure -> Structure 
addToStrct a (Structure b xs) = Structure b ((newStrct a):xs) 

insert :: String -> String -> Structure -> Structure 
insert a b (Structure c xs) 
    | a == c = addToStrct b (Structure c xs) 
    | search a (Structure c xs) /= newStrct "Not found" = addToStrct b (search a (Structure c xs)) 

問題は、次のとおりです。
は のは、私がこのような構造を持っていると仮定しましょう

J 
    K 
    L 

最初の問題は、私がしたいとき構造体「K」に新しい構造体「M」を挿入し、これを出力する

012代わりに、この

J 
    K 
    M 
    L 

そして第二の

は、私は指定された構造を見つけるための試みで私の主な構造のすべての構造体のすべてのリストを実行する方法がわからないということです。

アイデア?私は今、より明確に願っています。ありがとう

+0

また、複数の一致がある場合はどうなりますか? – karakfa

+0

私はアマチュアエラーのため申し訳ありません、私はそのより明確な今すぐ希望@ 4castle –

+0

それは "最も古い"を選択する必要があります、申し訳ありません私は以前の@karakfaを明確にしていない –

答えて

1

あなたの用語は少し曖昧ですが、あなたは別の構造に「挿入」したいと言います。ハスケルでは、これは不可能です。構造体を変更することはできません。新しい構造体を作成するだけです。 Haskellでこれを行う方法は、以前の構造と同じ新しい構造を作成することですが、その中に新しい項目が1つあります。あなたの質問は少し漠然としているので、これがあなたの問題を解決するかどうかを判断するのは少し難しいですが、私はそれを始めるには良い場所だと思います。

addStructure :: Structure -> Structure -> Structure 
addStructure (Structure str ls) struct = Structure str (struct:ls) 

emptyStructure :: String -> Structure 
emptyStructure str = Structure str [] 

insert :: String -> String -> Structure -> Structure 
insert s1 s2 struct = addStructure struct $ addStructure (emptyStructure s1) $ emptyStructure s2 
+0

私は、ウッドストック。とにかくありがとう! –

関連する問題