programing

목록과 구분자를 연결하는 haskell 기능이 있나요?

starjava 2023. 4. 22. 08:22
반응형

목록과 구분자를 연결하는 haskell 기능이 있나요?

리스트의 요소를 구분자로 연결하는 기능이 있습니까?예를 들어 다음과 같습니다.

> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]

답장 감사합니다!

, 있습니다.

Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"

intersperse 조금 더 일반적입니다.

Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"

또, 스페이스 문자를 사용해 결합하는 경우는, 다음과 같습니다.

Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"

unlines 마찬가지로 동작하는 것은 문자열이 newline 문자를 사용하여 삽입되고 newline 문자가 끝에 추가되는 경우뿐입니다(이를 통해 POSIX 표준 말미에 후행의 newline이 있는 텍스트파일 시리얼화에 도움이 됩니다).

폴더를 사용하여 원라이너를 쓰는 것은 어렵지 않습니다.

join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]

관심이 있는 경우, 인터스페스 및 인터컬레이트 구현에 대한 몇 가지 다른 아이디어:

myIntersperse :: a -> [a] -> [a]
myIntersperse _ [] = []
myIntersperse e xs = init $ xs >>= (:[e])

myIntercalate :: [a] -> [[a]] -> [a]
myIntercalate e xs = concat $ myIntersperse e xs

xs >>= f와 동등하다concat (map f xs).

joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont

자신의 버전을 쓰고 싶다면intercalate그리고.intersperse:

intercalate :: [a] -> [[a]] -> [a]
intercalate s [] = []
intercalate s [x] = x
intercalate s (x:xs) = x ++ s ++ (intercalate s xs)

intersperse :: a -> [a] -> [a]
intersperse s [] = []
intersperse s [x] = [x]
intersperse s (x:xs) = x : s : (intersperse s xs)

언급URL : https://stackoverflow.com/questions/9220986/is-there-any-haskell-function-to-concatenate-list-with-separator

반응형